CSS盒子水平居中
比如有一个DIV盒子,如果不给任何样式,默认的宽度是和浏览器一样宽的(如下图所示)。
那么若要让盒子里面的内容居中对齐,我们可以设定如下样式:
div {
text-align: center;
}
这里的内容包括文字、行内元素、行内块元素。
盒子本身是可以指定宽度和高度的,我们可以设定如下样式:
div {
text-align: center;
width: 300px;
height: 100px;
background-color: deeppink;
}
这里我们可以发现盒子里面的内容对于盒子而言是居中对齐的,但是盒子本身对于页面而言却不是居中对齐的。
接下来就是本节需要介绍的——如何让盒子水平居中?
可以在样式中如下进行设置:
div {
text-align: center;
width: 300px;
height: 100px;
background-color: deeppink;
margin: 0 auto;/*上下是0,左右是自动*/
}
或者
div {
text-align: center;
width: 300px;
height: 100px;
background-color: deeppink;
margin-left: auto;
margin-right: auto;
}
或者
div {
text-align: center;
width: 300px;
height: 100px;
background-color: deeppink;
margin: auto;
}
上述三种方式效果都是一样的,所以以后我们见到了千万不要慌张。
总结1:
文字水平居中我们用 text-align: center;盒子水平居中我们用 margin: 0 auto;
总结2:
可以让一个盒子实现水平居中,需要满足以下两个条件:
1、必须是块级元素;2、盒子必须指定宽度(Width);
然后就给左右的外边距都设置为auto,就可以使块级元素水平居中。
实际工作中常用这种方式进行网页的布局。
【完整样式代码】
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>盒子水平居中</title><style>div { text-align: center; /*盒子的内容居中对齐*/width: 300px;height: 100px;background-color: deeppink;margin: 0 auto; /*上下是0,左右是自动*/margin-left: auto;margin-right: auto;}</style></head><body><div>盒子</div></body></html>