1、利用text-align:center让子元素居中,子元素应为行内元素或行间块状元素。
2、利用width和margin水平居中,需要设置宽度和margin-left:auto、margin-right:auto,必须要块状元素才行。
<div style="background-color:red;height:300px;">
<div style="backgroundcolor:blue;height:100px;margin:auto;width:200px;display:block">
nnnnnnnnnnnn
</div>
</div>
3、利用双重定位实现水平居中。父元素绝对定位,left:50%;子元素相对定位,right:50%;这能自适应宽度。
<div style="background-color:red;position:absolute;left:50%">
<div style="background-color:blue;height:100px;width:200px;position:relative;right:50%">
jjjSnnnnnnnnnnnn
</div>
</div>
4、使用display:table-cell来居中,模拟一个表格单元格,父元素需要设置宽度,子元素需要设置为行间块状元素,可以自适应宽度。
<div style="background-color:red;display:table-cell;text-align:center;width:500px;">
<div style="background-color:blue;height:100px;width:150px;display:inline-block">
jjjSnnnnnnnnnnnn
</div>
</div>
5、利用负margin和定位,这需要设置子元素宽度,left:50%,margin-left:width/2。
<div style="background-color:red;height:500px;">
<div style="background-color:blue;height:100px;width:200px;position:relative;left:50%;margin-left:-100px;">
jjjSnnnnnnnnnnnn
</div>
</div>
6、浮动,绝对定位,固定定位后,元素都是行间块状元素,但是相对定位还是原来的属性。
7、固定定位后,left、height等设为百分比时,是相对浏览器的百分比,而不是其父容器;但是相对定位就是其父容器的百分比;绝对定位是其第一个非static定位的祖先元素。
8、浮动后元素自动变为行间块状元素,百分比相对父元素,浮动会引起父元素坍塌。
9、利用transform,自适应宽高实现水平垂直居中
<div class="box6">
woainiyaooofffffffffffffffffff
</div>
<style>
.box6 {
position: absolute;
top:50%;
left:50%;
background-color:red;
transform:translate(-50%,-50%);
text-align: center;
}
</style>
10、利用margin和0实现固定宽高水平垂直居中
<div class="box6">
woainiyaooofffffffffffffffffff
</div>
<style>
*{
padding:0px;
margin:0px;
}
.box6 {
width: 50%;
height: 50%;
background: #000;
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
</style>
11、在确定宽高的情况下,利用绝对定位和-margin: 宽/2,高/2
<div class="box6">
woainiyaoo
</div>
<style>
*{
padding:0px;
margin:0px;
}
.box6 {
position: absolute;
width:100px;
height: 50px;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-25px;
text-align: center;
background-color:red;
}
12、利用flex实现水平垂直居中,自适应宽高
<div class="box6" >
<p style="background-color:blue;">woainiyaof</p>
</div>
<style>
*{
padding:0px;
margin:0px;
}
.box6 {
width: 500px;
height: 550px;
display:inline-flex;
align-items:center;
justify-content: center;
background-color:red;
}
</style>