css水平居中

内联元素居中

text-align: center;
我是内容

块级元素居中

确定宽度

1. margin和width实现水平居中

我是内容

 

<div style="width: 50%; background: #f06d06; margin: 0 auto;">我是内容</div>

 

2. 绝对定位,margin-left: -(宽度值/2)

.content{
  width: 200px;
  position: absolute;
  left: 50%;
  margin-left: -100px; // 该元素宽度的一半,即100px
}
我是内容

 

3.绝对定位,left=0,top=0,right=0,bottom=0 , margin:auto

<div style="position:relative">
  <
div style="position: absolute; width: 200px; top: 0; right: 0; bottom: 0; left: 0; margin: auto; background-color: #f06d06;">我是内容</div>
</div>
我是内容

不确定宽度

1.父元素text-align: center;子元素 display: inline-block

<div style="text-align: center;">
  <div style="display: inline-block; background-color: #f06d06;">我是内容</div>
</div>
我是内容
2.父元素position: relative;子元素position: absolute; left: 50%; transform: translateX(-50%);
我是内容
<div style="position: relative; height: 50px;">
<div style="position: absolute; left: 50%; transform: translateX(-50%); background-color: #f06d06;">我是内容</div>
</div>

3.CSS3弹性盒子

我是内容
<div style="display: flex; justify-content: center;">
  <div style="background-color: #f06d06;">我是内容</div>
</div>

 

posted @ 2021-12-06 11:11  白色的月  阅读(51)  评论(0)    收藏  举报