css 实现水平居中

 
水平居中分为块状元素和行内元素,而块状元素又分为定宽块状元素和不定宽块状元素。
1、行内元素水(display: inline)平居中(文本、图片等)是通过给父元素设置 text-align:center;来实现的。
<p style="text-align: center;">行内元素水平居中</p>
2、定宽块状元素(dispaly: block)水平居中(块状元素的width是一个固定值),满足块状和定宽两个条件时,即可通过给自己设置“左右margin为auto”来实现。
<div style="width: 200px; text-align: center; margin: 0 auto;">定宽块状元素水平居中</div>
3、不定宽块状元素水平居中
1) 改变块状元素的 dispaly 属性为 inline, 然后给父级设置 text-aline:center 来实现水平居中, 这种方法的缺点是不能再给元素设置宽高了
<div style="text-align: center;">
       <div style="display: inline;">不定宽块状元素水平居中</div>        
</div>
2) 利用绝对定位,让元素向右偏移50%,然后再向左偏移自身的50%
<div style="position: absolute; left: 50%; transform: translateX(-50%);">不定宽块状元素水平居中</div>
3) 利用flex实现水平居中(一)
<div style="display: flex;">
     <div style="margin: 20px auto;">不定宽块状元素水平居中</div>
</div>
4) 利用flex实现水平居中(二)CSS3的fit-content配合左右margin为auto实现水平居中方法
<div style="width: fit-content; margin-left: auto; margin-right: auto;">不定宽块状元素水平居中</div>

猜你喜欢

转载自www.cnblogs.com/00feixi/p/10116877.html
今日推荐