CSS水平居中总结

CSS水平居中总结

行内元素

如果被设置元素为文本、图片等行内元素时,水平居中是通过给父元素设置 text-align:center 来实现的。

html代码:

1
2
3
<body>
<div class="txtCenter">我想要在父容器中水平居中显示。</div>
</body>

css代码:

1
2
3
4
5
<style>
.txtCenter{
text-align:center;
}
</style>

块状元素

定宽块状元素

定宽块状元素:块状元素的宽度width为固定值。

满足定宽和块状两个条件的元素是可以通过设置“左右margin”值为“auto”来实现居中的。

html代码:

1
2
3
<body>
<div>我是定宽块状元素,哈哈,我要水平居中显示。</div>
</body>

css代码:

1
2
3
4
5
6
7
<style>
div{
border:1px solid red;/*为了显示居中效果明显为 div 设置了边框*/
width:200px;/*定宽*/
margin:20px auto;/* margin-left 与 margin-right 设置为 auto */
}
</style>

也可以写成:

1
2
margin-left:auto;
margin-right:auto;

注意:元素的“上下 margin” 是可以随意设置的。

文章目录
  1. 1. CSS水平居中总结
    1. 1.1. 行内元素
    2. 1.2. 块状元素
|