1.使用text-align:center/line-height:高度一半进行居中
![](https://img.haomeiwen.com/i7988335/54b3f2b0443c17fd.png)
.center1 {
width: 100px;
height: 100px;
background-color: cadetblue;
text-align: center;
line-height: 100px;
margin: auto;
}
html
<div class="center1">水平文字居中</div>
- 这种居中,如果不设置宽高,则会铺满整个父元素
-
position方法之:transform: translate(-50%, -50%); top:50% left:50%
image.png
.outer2 {
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
/*写在父元素上,绝对定位*/
}
.center2 {
width: 100px;
height: 100px;
background-color: antiquewhite;
position: absolute;
/*写在子元素上,相对定位,相对父元素定位*/
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
html
<div class="outer2">
<div class="center2">水平垂直居中(未知宽高)</div>
</div>
- position方法之: margin: -50px 0 0 -50px;(宽高一半)
.outer3 {
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
/*写在父元素上,绝对定位*/
}
.center3 {
width: 100px;
height: 100px;
background-color: antiquewhite;
position: absolute;
/*写在子元素上,相对定位,相对父元素定位*/
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}
- position方法之: top: 0;left: 0;right: 0;bottom: 0;
.outer4 {
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
/*写在父元素上,绝对定位*/
}
.center4 {
width: 100px;
height: 100px;
background-color: antiquewhite;
position: absolute;
/*写在子元素上,相对定位,相对父元素定位*/
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
5.水平垂直居中内联元素
.outer5 {
width: 200px;
height: 200px;
border: 1px solid red;
display: flex;
justify-content: center;
/*水平居中*/
align-items: center;
/*垂直居中*/
}
.center5 {
width: 100px;
height: 100px;
background-color: blueviolet;
}
下面几个效果图都如上图
网友评论