温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

css设置垂直居中的几种方法

发布时间:2021-04-22 09:30:45 来源:亿速云 阅读:216 作者:栢白 栏目:web开发

这篇文章主要介绍了css设置垂直居中的几种方法,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。

1、使用line-height属性让文字垂直居中;2、使用CSS3 flex布局让文字垂直居中;3、使用绝对定位和transform让块状元素垂直居中;4、使用flex布局让块状元素垂直居中。

css设置文本文字垂直居中

1、line-height 使文字垂直居中

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
    width: 300px;
    height: 300px;
    background: paleturquoise;
    line-height:300px;
}
</style>
</head>
<body>
<div class="box">css 垂直居中了--文本文字</div>
</body>
</html>

效果图:

css设置垂直居中的几种方法

这样就能让div中的文字水平垂直居中了

2、CSS3的flex布局 使文字垂直居中

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
   width: 300px;
   height: 200px;
   background: paleturquoise;
   /*设置为伸缩容器*/
   display: -webkit-box;
   display: -moz-box;
   display: -ms-flexbox;
   display: -webkit-flex;
   display: flex;
   /*垂直居中*/
   -webkit-box-align: center;/*旧版本*/
   -moz-box-align: center;/*旧版本*/
   -ms-flex-align: center;/*混合版本*/
   -webkit-align-items: center;/*新版本*/
   align-items: center;/*新版本*/
}
</style>
</head>
<body>
<div class="box">css 垂直居中--文本文字(弹性布局)</div>
</body>
</html>

效果图:

css设置垂直居中的几种方法

css设置块状元素垂直居中

1、使用绝对定位和transform(未知元素高度)

如果我们不知道元素的高度,那么就需要先将元素定位到容器的中心位置,然后使用 transform 的 translate 属性,将元素的中心和父容器的中心重合,从而实现垂直居中:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
width: 300px;
    height: 300px;
    background: #ddd;
    position: relative;
}
.child{
background: #93BC49;
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
}
</style>
</head>
<body>
<div class="box">
    <div class="child">css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中</div>
</div>
</body>
</html>

效果图:

css设置垂直居中的几种方法

2、使用flex布局

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
width: 300px;
    height: 300px;
    background: #ddd;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
.child{
width: 300px;
    height: 100px;
    background: #08BC67;
    line-height: 100px;
}
</style>
</head>
<body>
<div class="box">
    <div class="child">css 垂直居中了--弹性布局</div>
</div>
</body>
</html>

效果图:

css设置垂直居中的几种方法

以上就是css设置垂直居中的几种方法的详细内容了,看完之后是否有所收获呢?如果想了解更多相关内容,欢迎来亿速云行业资讯!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI