方法1、使用text-align: center;
使用text-align: center;
可以将块级元素(父元素)中的行内元素进行水平居中;直接给父元素设置 text-align: center;
即可。
<style> #father { width: 500px; height: 300px; background-color: skyblue; text-align: center; } </style> <div id="father"> <span id="son">我是行内元素</span> </div>
如果父元素不是块级元素,需先将其父元素设置为块级元素,然后在给父元素设置text-align: center;
规则即可。
<style> #father { display: block; width: 500px; height: 300px; background-color: skyblue; text-align: center; } </style> <span id="father"> <span id="son">我是行内元素</span> </span>
效果图:
方法2:使用margin: 0 auto;
使用margin: 0 auto;
可以将块级元素(父元素)中具有固定宽度的块级元素进行水平居中;此时需要谁居中,就给其设置 margin: 0 auto;
(作用:使盒子自己居中)。
<style> #father { width: 500px; height: 300px; background-color: skyblue; } #son { width: 100px; height: 100px; background-color: green; margin: 0 auto; } </style> <div id="father"> <div id="son">我是块级元素</div> </div>
效果:
方法3:使用定位属性
首先设置父元素为相对定位,再设置子元素为绝对定位,设置子元素的left:50%,即让子元素的左上角水平居中;
固定宽度:设置绝对子元素的 margin-left: -元素宽度的一半px;
或者设置transform: translateX(-50%);
<style> #father { width: 500px; height: 300px; background-color: skyblue; position: relative; } #son { width: 100px; height: 100px; background-color: green; position: absolute; left: 50%; margin-left: -50px; } </style> <div id="father"> <div id="son">我是块级元素</div> </div>
不定宽度:利用css3新增属性transform: translateX(-50%);
<style> #father { width: 500px; height: 300px; background-color: skyblue; position: relative; } #son { height: 100px; background-color: green; position: absolute; left: 50%; transform: translateX(-50%); } </style> <div id="father"> <div id="son">我是块级元素</div> </div>
效果:
方法4:使用flexbox布局实现(宽度定不定都可以)
使用flexbox布局,只需要给待处理的块状元素的父元素添加属性 display: flex;
justify-content: center;
<style> #father { width: 500px; height: 300px; background-color: skyblue; display: flex; justify-content: center; } #son { width: 100px; height: 100px; background-color: green; } </style> <div id="father"> <div id="son">我是块级元素</div> </div>
效果:
以上就是CSS中水平居中怎么设置?的详细内容,更多请关注0133技术站其它相关文章!