如何让盒子水平居中
在开发中我们会经常需要让一个盒子进行水平居中来达到某种效果,水平居中也是我们在开发中用到最多的!
1.让块级元素水平居中
HTML
<div class="box">
我是box盒子
<div class="one">我是one盒子</div>
</div>
CSS
<style>
.box {
width: 300px;
height: 300px;
background-color: cornflowerblue;
margin: 0 auto;/* 在浏览器中水平居中 */
}
.one{
width: 100px;
height: 100px;
background-color: #ff6600;
margin: 0 auto; /* 给子盒子添加margin属性实现在父盒子中水平居中 */
}
</style>
效果如下:
//为了让大家看的更清楚添加了文字,所以one盒子会距离上面有一段距离。
让块级盒子居中的方法非常简单,就是给块元素的盒子一个margin:0 auto属性。
2.让行内元素,行内块元素文本在盒子内进行水平居中
HTML
<div class="box">
<span>我是行内元素</span>
</div>
CSS
<style>
.box {
width: 300px;
height: 300px;
background-color: cornflowerblue;
text-align: center;/* 让文本水平居中 */
}
</style>
让行内元素和行内块元素水平居中的方法就是给其父元素添加text-align: center;
效果图如下:
总结!!!
- 让行内元素 行内块元素 和文本水平居中的方法就是给其父元素添加text-align: center; 。
- 让块元素水平居中的方法就是给需要居中的盒子 添加margin: 0 auto; 。
- 行内块 和行内元素 添加**display: block;**转换成块元素后可以使用 margin: 0 auto; 进行水平居中。