-
text-align:center;
text-align: center; 使标签内部的文本居中 是可遗传的
<body>
<style>
div{
text-align: center;
width: 300px;
height: 100px;
background: #3EFD9B;
}
</style>
<div>
我是div
</div>
</body>
如图:
text-align: center; 他的属性不仅仅只是让里面的文本居中文本级标签也是可以居中的
<body>
<style>
div{
text-align: center;
width: 300px;
height: 100px;
background: #3EFD9B;
}
span{
background: #2db5bc;
}
</style>
<div>
<span>我是div</span>
</div>
</body>
如图:
里面的行内块级标签也是可以用这个方法居中的 至于为什么我也不是很清楚还望有知道的可以评论
<body>
<style>
div{
text-align: center;
width: 300px;
height: 100px;
background: #3EFD9B;
}
h{
display: inline-block;
background: #2db5bc;
}
</style>
<div>
<h>我是div</h>
</div>
</body>
如图
-
最喜欢用的还是 margin: 0 auto; 首先需要实际的宽度 还需要是块级元素 行内块级不行哦
另外发现没有 里面的strong这个标签是没有居中的哦
也就是说 margin: 0 auto; 是不会被遗传的
<body>
<style>
div{
width: 300px;
height: 100px;
background: #3EFD9B;
margin: 0 auto;
}
strong{
display: block;
width: 50px;
height: 50px;
background: #2db5bc;
}
</style>
<div>
<strong>我是strong</strong>
</div>
</body>
所以我一般都喜欢 一个通变符(星号) *{ margin: 0 auto;} 这样只要我给了它实际的宽度他就自己居中了
<body>
<style>
*{
margin: 0 auto;
}
div{
width: 300px;
height: 100px;
background: #3EFD9B;
/*margin: 0 auto;*/ /*这里就可以不写了*/
}
strong{
display: block;
width: 50px;
height: 50px;
background: #2db5bc;
}
</style>
<div>
<strong>我是strong</strong>
</div>
</body>
-
当然垂直也是可以居中的 但我只知道 line-height:调试到居中就好;大多数都是相对于那个标签居中就调成和它的高度一致 可遗传
<body>
<style>
div{
width: 300px;
height: 100px;
background: #3EFD9B;
margin: 0 auto;
line-height: 100px;
}
</style>
<div>
我是strong
</div>
</body>
当然还有很多列入flex布局center;justify-content水平居中 align-items:center垂直居中 就不说了 那个是flex