<!--使一个div居中-->
<div>
1
1
1
</div>
/*div宽高未知:通过绝对定位和transform*/
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #AFEEEE;
}
/*div宽高已知:通过绝对定位和margin*/
div {
position: absolute;
top: 50%;
left: 50%;
margin: -100px;
width: 200px;
height: 200px;
background-color: #AFEEEE;
}
/*div宽高已知或未知:通过flex布局和margin*/
body {
display: flex;
/*必须设置min-height为100vh*/
min-height: 100vh;
/*margin: 0;*/
}
div {
margin: auto;
/*此方法宽高已知未知都适用*/
/*width: 200px;
height: 200px;*/
background-color: #AFEEEE;
}
/*div宽高已知或未知:通过flex布局*/
body {
display: flex;
/*必须设置min-height为100vh*/
min-height: 100vh;
justify-content: center;
align-items: center;
}
div {
/*此方法宽高已知未知都适用*/
/*width: 200px;
height: 200px;*/
background-color: #AFEEEE;
}
<!--使div中的p元素居中-->
<div>
<p>1</p>
</div>
/*使用flex布局*/
div {
display:flex ;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background-color: #AFEEEE;
}
/*使用table-cell和对齐*/
div {
display: table-cell;
text-align: center;
vertical-align: middle;
/*position: relative;
overflow:hidden;*/
width: 200px;
height: 200px;
background-color: #AFEEEE;
}
* {
margin:0;
padding:0;
}