05你认真学了css?元素居中

一、元素水平居中

1、text-align实现水平居中

text-align:center; 行内元素(图片或文字)居中
在父元素上设置text-align: center 使文字/图片在整个页面上水平居中

1
2
3
 .container{
text-align:center;
}

如一小选项按钮居中,可以使用:

1
2
3
4
 .container{
display:inline-block;
text-align:center;
}

2、margin实现水平居中

margin: 0 auto; 用于块级元素的居中

1
2
3
4
5
6
.container {
width: 80%; /*块级元素充满页面 定宽必备 */
margin-left: auto;
margin-right: auto;
/*或者 margin:0 auto;*/
}

如:块级元素居中
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 <style>
.wrap{
max-width:600px;
background: #ccc;
margin: 0 auto;
}

</style>
</head>

<div class="wrap">
<h1>hello</h1>
<p>world</p>
</div>

image

二、元素垂直居中

1、居中 VS 不居中

注: 高度由里面的内容撑开,一般不设置高度
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
 <style>
.ct{
padding: 40px 0;
text-align: center;
background: #eee;
}
</style>

<div class="ct">
<p>你好世界</p>
<p>helloworld</p>
</div>

image

2、vertical-align实现垂直居中

vertical-align: middle; 让行内元素或表格元素相对于基线对齐并居中
案例:如图片进行水平、垂直居中
代码如下:图片在容器内水平、垂直居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<style>
.box{
width: 300px;
height: 200px;
border: 1px solid ;
text-align: center;
}
/*注:子元素和父元素分别设置 vertical-align:middle; ,均无法实现垂直居中*/

/*使用一个伪元素,设置一个虚拟的基准线*/
.box:before{
content: '';
display: inline-block;
height: 100%;
vertical-align: middle; ✔️
}
.box img{
vertical-align: middle; ✔️
background: blue;
}
</style>

<div class="box">
<img src="http://cdn.jirengu.com/public/logo-tiny.png" alt="">
</div>

如图:image

3、table-cell 实现垂直居中

display: table-cell;水平垂直居中
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<style>
.box{
width: 300px; /*由于是行内元素,宽度必备*/
height: 200px;
border: 1px solid ;
display: table-cell; ✔️
vertical-align: middle; ✔️
text-align: center;
}
</style>

<div class="box">
<img src="http://cdn.jirengu.com/public/logo-tiny.png" alt="">
</div>

4、绝对定位实现居中

案例:如弹出框 弹出框水平垂直居中
情况1: 固定宽高块在浏览器窗口水平垂直居中,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<style>
html,body {
height: 100%;
}
.dialog {
position: absolute; /*绝对定位*/
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -150px;

width: 400px;
height: 300px;
box-shadow: 0px 0px 3px #000;
}

.dialog .header{
padding: 10px;
background: #000;
color: #fff;
}
.dialog .content{
padding: 10px;
}
</style>

<div class="dialog">
<div class="header">我是标题</div>
<div class="content">我是内容</div>
</div>

image

情况2: 去掉宽高的块在浏览器窗口水平垂直居中,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<style>
html,body {
height: 100%;
}

.dialog {
position: absolute;
left: 50%;
top: 50%;
/* margin-left: -200px;
margin-top: -150px; */

/*CSS3属性 相对于自己的偏移*/
transform:translate(-50%,-50%);
box-shadow: 0px 0px 3px #000;
}

.dialog .header{
padding: 10px;
background: #000;
color: #fff;
}
.dialog .content{
padding: 10px;
}
</style>

<div class="dialog">
<div class="header">我是标题</div>
<div class="content">我是内容</div>
<div class="content">我是内容</div>
<div class="content">我是内容</div>
<div class="content">我是内容</div>
</div>

image

-------------本文结束感谢您的阅读-------------