css如何垂直居中一个元素的问题已是一个老生常谈的问题了。无论对于一个新手或者老手,在面试过程当中是常常被问到的。前两天在看一个flex的视频教程,当中提到了有关元素的居中问题,因此今天小编就来扒一扒几种常见的方式。不足之处请你们批评指正(全部的代码都是本身亲手敲过可用的)css
一、水平居中(margin:0 auto;) html
关于这个,你们应该是最不陌生的,无论是在培训班仍是本身自学的话 。这个应该是老师讲的第一个方法了(水平方向上),可是其有一个前提,就是被包裹的元素不能有浮动的属性。不然的话这个属性就会失效。具体以下图代码:css3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<style>
body{margin: 0;}
.box{
width: 400px;
height: 400px;
border:1px solid red;
}
item{
margin:0 auto;
width: 100px;
height: 100x;
background: green;
}
</style>
<body>
<div
class
=
"box"
>
<div
class
=
"item"
></div>
</div>
</body>
|
1
|
|
二、水平居中(text-align:center;)面试
这个属性在没有浮动的状况下,咱们能够将其转换为inline/inline-block,而后其父元素加上text-align:center;属性就能够将其居中flex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<
style
>
body{margin: 0;}
.box{
width: 400px;
height: 400px;
border:1px solid red;
text-align:center;
}
item{
display:inline/inline-block;
width: 100px;
height: 100x;
background: green;
}
</
style
>
<
body
>
<
div
class="box">
<
div
class="item"></
div
>
</
div
>
</
body
>
|
三、水平垂直居中(一) 子元素相对于父元素绝对定位,而且margin值减去本身宽高的一半spa
该方法具备必定的局限性,由于其必需要知道子元素自己的宽高3d
<style> body{margin: 0;} .box{ width: 400px; height: 400px; border:1px solid red; position: relative; } item{ position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; width: 100px; height: 100x; background: green; } </style> <body> <div class="box"> <div class="item"></div> </div> </body>
四、水平垂直居中(二) 子元素相对于父元素绝对定位,而且margin值位autocode
该方式不受元素宽高所限制,比较好用(推荐使用)orm
<style> body{margin: 0;} .box{ width: 400px; height: 400px; border:1px solid red; position: relative; } item{ position: absolute; left: 0; right: 0; bottom: 0; top:0; margin: auto; width: 100px; height: 100x; background: green; } </style> <body> <div class="box"> <div class="item"></div> </div> </body>
五、水平垂直居中(三) diplay:table-cell视频
该方式是将元素转换成表格样式,再利用表格的样式来进行居中(推荐)
<style> body{margin: 0;} .box{ width: 400px; height: 400px; border:1px solid red; display: table-cell; vertical-align: middle; } item{ margin:0 auto; width: 100px; height: 100x; background: green; } </style> <body> <div class="box"> <div class="item"></div> </div> </body>
六、水平垂直居中(四) 绝对定位和transfrom
该方法用最能装逼,用到了css3变形,面试者看到你代码里面有这样的 ,你的逼格瞬间就上去了,固然了 你知道的,逼格的东西是有兼容性问题的
<style> body{margin: 0;} .box{ width: 400px; height: 400px; border:1px solid red; position:relative; } item{ width: 100px; height: 100x; background: green; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); } </style> <body> <div class="box"> <div class="item"></div> </div> </body>
七、水平垂直居中(五)css3中的flex属性
这个属性很好用,可是绝逼有兼容性问题的,用者要注意
<style> body{margin: 0;} .box{ width: 400px; height: 400px; border:1px solid red; display: flex; justify-content: center; align-items: center; } item{ width: 100px; height: 100x; background: green; } </style> <body> <div class="box"> <div class="item"></div> </div> </body>