Linux 拨号vps windows公众号手机端

css如何实现垂直居中

lewis 6年前 (2019-03-15) 阅读数 11 #程序编程
文章标签 css

css实现垂直居中的方法:1、使用“line-height”属性使文字垂直居中,只需要在css中添加“line-height:300px;”样式来实现,其中300px表示宽度和行高相同。2、使用绝对定位“position: relative;”和负外边距“margin: -50px 0 0 0;”对块级元素进行垂直居中;3、使用绝对定位属性和“transform”的“translate”属性将元素的中心和父容器的中心重合实现垂直居中;4、使用flex布局(弹性布局)实现垂直居中即可。

具体内容如下:

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

<!DOCTYPEhtml>

<html>

<head>

<metacharset="UTF-8">

<title>css垂直居中</title>

<style>

.box{

width:300px;

height:300px;

background:#21B4BB;

color:#FFF;

line-height:300px;

}

</style>

</head>

<body>

<divclass="box">css垂直居中了--文本文字</div>

</body>

</html>

效果图:

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


2、使用绝对定位和负外边距对块级元素进行垂直居中 (已知元素的高度)


如果我们知道元素的高度,可以这样来实现垂直居中:


<!DOCTYPEhtml>

<html>

<head>

<metacharset="UTF-8">

<title>css垂直居中</title>

<style>

.box{

width:300px;

height:300px;

background:#ddd;

position:relative;

}

.child{

width:150px;

height:100px;

background:orange;

position:absolute;

top:50%;

margin:-50px000;

line-height:100px;

}

</style>

</head>

<body>

<divclass="box">

<divclass="child">css垂直居中</div>

</div>

</body>

</html>

效果图:

这个方法兼容性不错,但是有一个小缺点:必须提前知道被居中块级元素的尺寸,否则无法准确实现垂直居中。

3、使用绝对定位和transform进行垂直居中(未知元素高度

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


<!DOCTYPEhtml>

<html>

<head>

<metacharset="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>

<divclass="box">

<divclass="child">css垂直居中,css垂直居中,css垂直居中,css垂直居中,css垂直居中</div>

</div>

</body>

</html>

效果图:

这种方法有一个非常明显的好处就是不必提前知道被居中元素的尺寸了,因为transform中translate偏移的百分比就是相对于元素自身的尺寸而言的。


4. 使用flex布局


1)、使文字垂直居中


<!DOCTYPEhtml>

<html>

<head>

<metacharset="UTF-8">

<title>css垂直居中</title>

<style>

.box{

width:300px;

height:200px;

background:#21B4BB;

color:#FFF;

/*设置为伸缩容器*/

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>

<divclass="box">css垂直居中--文本文字(弹性布局)</div>

</body>

</html>

效果图:

2)、使块级元素(div)垂直居中


<!DOCTYPEhtml>

<html>

<head>

<metacharset="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>

<divclass="box">

<divclass="child">css垂直居中了--弹性布局</div>

</div>

</body>

</html>

效果图:



版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门