使用CSS元素居中的七种方法
在网页布局中元素水平居中比元素垂直居中要简单不少,同时实现水平居中和垂直居中往往是最难的。现在是响应式设计的时代,我们很难确切的知道元素的准确高度和宽度,所以一些方案不大适用。据我所知, 在CSS中至少有六种实现居中的方法。我将使用下面的HTML结构从简单到复杂开始讲解:
使用text-align水平居中
<div class="center">
<img src="jimmy-choo-shoe.jpg" alt>
</div>
使用 margin: auto 居中
div.center {
background: hsl(60, 100%, 97%);
}
div.center img {
display: block;
width: 33%;
height: auto;
margin: 0 auto;
}
注意: 必须使用display: block使 margin: 0 auto对img元素生效。
使用table-cell居中
### html
<div class="center-aligned">
<div class="center-core">
<img src="jimmy-choo-shoe.jpg">
</div>
</div>
### css
center-aligned {
display: table;
background: hsl(120, 100%, 97%);
width: 100%;
}
.center-core {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.center-core img {
width: 33%;
height: auto;
}
使用absolute定位居中
absolute-aligned {
position: relative;
min-height: 500px;
background: hsl(200, 100%, 97%);
}
.absolute-aligned img {
width: 50%;
min-width: 200px;
height: auto;
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0;
bottom: 0; right: 0;
}
使用translate居中
.center {
background: hsl(180, 100%, 97%);
position: relative;
min-height: 500px;
}
.center img {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
width: 30%; height: auto;
}
使用Flexbox居中
.center {
background: hsl(240, 100%, 97%);
display: flex;
justify-content: center;
align-items: center;
}
.center img {
width: 30%; height: auto;
}
使用calc居中
在某些情况下比flexbox更全面:
.center {
background: hsl(300, 100%, 97%);
min-height: 600px;
position: relative;
}
.center img {
width: 40%;
height: auto;
position: absolute;
top: calc(50% - 20%);
left: calc(50% - 20%);
}
很简单,calc 允许你基于当前的页面布局计算尺寸。在上面的简单计算中, 50% 是容器元素的中心点,但是如果只设置50%会使图片的左上角对齐div的中心位置。 我们需要把图片向左和向上各移动图片宽高的一半。计算公式为:
top: calc(50% - (40% / 2));
left: calc(50% - (40% / 2));
在现在的浏览其中你会发现,这种方法更适用于当内容的宽高为固定尺寸:
.center img {
width: 500px; height: 500px;
position: absolute;
top: calc(50% - (300px / 2));
left: calc(50% - (300px – 2));
}
这种方案和flex一样有许多相同的缺点: 虽然在现代浏览器中有良好的支持,但是在较早的版本中仍然需要浏览器前缀,并且不支持IE8。
.center img {
width: 40%; height: auto;
position: absolute;
top: calc(50% - 20%);
left: calc(50% - 20%);
}
更详细内容请查看原文地址:
点击我查看
如果对您有帮助,您又乐意的话,请多多支持!

