假设父元素的position: relative;
,这四个属性将使子元素在内部水平和垂直居中,无论它们的高度宽度是多少。
@mixin centerer {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.parent {
position: relative;
}
.child {
@include centerer;
}
见钢笔中心件的Mixin克里斯Coyier( @chriscoyier上) CodePen 。
尽管要注意,如果居中的子元素比父元素高,则顶部可能会被切断。
范西尔
如果您只想在一个方向上居中...
@mixin centerer($horizontal: true, $vertical: true) {
position: absolute;
@if ($horizontal and $vertical) {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
} @else if ($horizontal) {
left: 50%;
transform: translate(-50%, 0);
} @else if ($vertical) {
top: 50%;
transform: translate(0, -50%);
}
}
在CodePen上查看Chris Coyier ( @chriscoyier )的Pen yybgZd 。