text-align与margin:0 auto的居中问题
.ABOUT .about-top .a{
width: 100%;
font-size: 40px;
font-weight: bolder;
padding-top:80px;
text-align: center;
}
.ABOUT .about-top .line{
width: 35px;
height: 2px;
background-color: #07cbc9;
margin: 0 auto;
}<div class="ABOUT"> <div class="about-top"> <div class="a">ABOUT</div> <div class="line"></div> </div> </div>

about用text-align,线段用margin:0 auto才可以居中,两者互换就不可以,但是这两个不都是在<div>块内吗?
2
收起
正在回答
1回答
text-align是设置文本的水平对齐,而margin:0 auto,是设置里面的div相对于外面的div对齐,可以看一下下面的代码和运行效果:
这里把width为100%改为了200px,是这个具体值,100%宽度就会充满外面的div。把text-align注释掉了,而添加了margin:0 auto,可以看到,橘色的div相对于外面的div是居中的,而里面的文字因为没有设置text-align:center而没有相对于橘色的div居中。


下面是改好的样例代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>测试</title>
<style>
.ABOUT .about-top .a{
width: 200px;
font-size: 40px;
font-weight: bolder;
padding-top:80px;
/* text-align: center;*/
background-color: orange;
margin:0 auto;
}
.ABOUT .about-top .line{
width: 35px;
height: 2px;
background-color: #07cbc9;
margin: 0 auto;
}
.ABOUT{
width: 300px; height: 300px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="ABOUT">
<div class="about-top">
<div class="a">ABOUT</div>
<div class="line"></div>
</div>
</div>
</body>
</html>祝学习愉快!
从网页搭建入门Java Web2018版
- 参与学习 人
- 提交作业 1088 份
- 解答问题 10204 个
如果你有Java语言基础,又想以后从事Java Web开发,那么本路径是你的不二选择!本路径从网页搭建开始入手,通过大量案例来学习Java Web基础。定能助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星