- 水平居中:
①内联元素:爸爸身上写text-align:center;
②块状元素:margin-left:auto;margin-right:auto;
- 文字垂直居中:
让height
高度和line-height
高度一样; - 垂直居中:
①运用<table>
自带的属性;
<table class="baba">
<tr>
<td>
你好
</td>
</tr>
</table>
table{
height:600px;
border:1px solid red;
} //文字自动垂直居中
②margin:auto;
配合position:absolute;
上下左右都为0,需要给定宽高:(都为0就水平垂直居中)
<div class="parent">
<div class="child">
你好
</div>
</div>
.parent{
height: 600px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
position: absolute;
width: 300px;
height:40px;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
line-height:40px;
}
③position:absolute; top:50%; left:50%; transform:translate(-50%,-50%)
(不用给定宽高,这种最方便)
<div class="parent">
<div class="child">
你好
</div>
</div>
.parent{
height: 600px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
④flex
布局:父元素上写display: flex; justify-content: center; align-items: center;
<div class="parent">
<div class="child">
你好
</div>
</div>
.parent{
height: 600px;
border: 3px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.child{
border: 3px solid green;
}
网友评论