在使用css布局时会碰到各种各样的居中问题,在这里总结几种情况,希望大家纠错和补充.
文字
文字需要居中的情况有这么两种
水平居中
- text-align常常用于盒子里的文字、图片等内容居左、居中、局右。比较常见是常规的让内容居左或居中对齐排列.text-align:center
垂直居中
- 在一排的文字或内容布局中,如果要让内容上下垂直居中,我们只需要设置line-height与height高度相同即可
div元素
水平居中
使用margin:0 auto即可
水平并且垂直居中
方法一:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
.container{
width:800px;
height:400px;
position: relative;
background-color: #CCCCCC;
}
.box{
background-color: #ffcc00;
width:300px;
height:200px;
position:absolute;
top:calc(50% - 100px);
left:calc(50% - 150px);
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
方法二:
.box{
background-color: #ffcc00;
width:300px;
height:200px;
position:absolute;
top:50%;
left:50%;
margin:-100px 0 0 -150px;
}
方法二只需要修改.box这个样式即可
第一种方法用到了calc函数.因为position这个属性,box相对于父元素定位,calc函数准确计算出了box居中所需要的left和top值.
第二种方法与第一种有些相似,box也是相对于父元素定位,先用百分比设定top和left值margin,再利用margin进行调整.
方法三:
.box{
background-color: #ffcc00;
width:300px;
height:200px;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
}
绝对定位下top left right bottom 都设置0,再margin: auto 就可以将元素垂直水平居中.
绝对定位的布局取决于三个因素,一个是元素的位置,一个是元素的尺寸,一个是元素的margin值。
而没有设置尺寸和 margin 的元素会自适应剩余空间,位置固定则分配尺寸,尺寸固定边会分配 margin,都是自适应的