水平居中
1.文字、图片等行内元素的水平居中
- 单行文字: 给父元素设置 text-align: center 即可
- 多行文字: 看作一个块级元素处理(后面会有介绍)
2.确定宽度的块元素的水平居中
- 元素为块级元素或行内元素设置 display: block
- 设置元素的 margin-left: auto 和 margin-right: auto
<style>
.background{
background-color: #666;
width: 400px;
height: 200px;
}
.text{
background-color: #eee;
width: 150px;
height: 100px;
margin-left: auto;
margin-right: auto;
}
</style>
<div class="background">
<div class="text"></div>
</div>
效果如图:
3.不确定的块元素的水平居中
方法一:
- 利用 table 标签,通过设置 margin-left: auto 和 margin-right: auto 来实现 table 居中,间接使其中的内容居中
- 缺点:增加了无语义标签,加深了标签的嵌套层数
<style>
.background{
background-color: #666;
width: 400px;
}
table{
margin-left: auto;
margin-right: auto;
}
table span{
background-color: #31b;
color: #fff;
margin: 3px;
padding: 3px;
}
</style>
<div class="background">
<table>
<tr>
<td>
<span>1</span>
<span>2</span>
<span>3</span>
</td>
</tr>
</table>
</div>
效果如图:
方法二:
- 利用 display: inline 将块级元素转化为行内元素,然后使用 text-align: center 实现居中
- 缺点:将块级元素转化为行内元素,而行内元素比块级元素缺少一些功能,这种方法会带来一些限制,例如设定长宽值
<style>
.background{
background-color: #666;
width: 400px;
text-align: center;
}
.background p{
display: inline;
background-color: #31b;
color: #fff;
margin: 3px;
padding: 3px;
}
</style>
<div class="background">
<p>1</p>
<p>2</p>
<p>3</p>
</div>
效果图:
方法三:
- 父元素设置 float,position: relative 和 left: 50%
- 子元素设置 position: relative,left:-50%
- 缺点:position: relative 会带来一定的副作用
<style>
.background{
background-color: #368;
width: 500px;
height: 150px;
}
.test{
float: left;
position: relative;
left: 50%;
}
.test p{
position: relative;
left: -50%;
color: #fff;
}
</style>
<div class="background">
<div class="test">
<p>1</p>
<p>2</p>
<p>3</p>
</div>
</div>
效果图:
欢迎补充!