使用 display flex 将多个项目居中
Centering multiple items with display flex
我想使用 justify-content: center 和 align-items: center 将 div 置于页面的绝对中心,但 div 需要是 100% 的宽度和高度页面的绝对中心。
当你在div的顶部或底部添加元素时,问题就来了,这降低了我们要居中的div的高度,不再处于绝对中心.
这是页面https://jsfiddle.net/nybf8tjc/1
我可以添加
.typewriter{margin-top: -41px;}
解决这个问题,但我觉得一定有更好的方法来解决这个问题。
你可以用这个简单的实现。
div.father {
width: 100vw;
height: 100vw;
position: absolute;
display: flex;
align-items: center;
justify-content: space-around;
}
div.father div.child {
width: 400px;
height: 250px;
background-color: teal;
position: relative;
}
<div class="father">
<div class="child"></div>
</div>
您也可以使用 transform
属性:
div.child {
width: 400px;
height: 250px;
margin:0;
padding: 0;
background-color: teal;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
这应该使您想要的容器居中。
看看https://css-tricks.com/snippets/css/a-guide-to-flexbox/
您可以使 .typewriter
成为一个绝对定位的元素,并添加通常的居中设置,例如
.typewriter {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
etc.
}
我想使用 justify-content: center 和 align-items: center 将 div 置于页面的绝对中心,但 div 需要是 100% 的宽度和高度页面的绝对中心。
当你在div的顶部或底部添加元素时,问题就来了,这降低了我们要居中的div的高度,不再处于绝对中心.
这是页面https://jsfiddle.net/nybf8tjc/1 我可以添加
.typewriter{margin-top: -41px;}
解决这个问题,但我觉得一定有更好的方法来解决这个问题。
你可以用这个简单的实现。
div.father {
width: 100vw;
height: 100vw;
position: absolute;
display: flex;
align-items: center;
justify-content: space-around;
}
div.father div.child {
width: 400px;
height: 250px;
background-color: teal;
position: relative;
}
<div class="father">
<div class="child"></div>
</div>
您也可以使用 transform
属性:
div.child {
width: 400px;
height: 250px;
margin:0;
padding: 0;
background-color: teal;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
这应该使您想要的容器居中。 看看https://css-tricks.com/snippets/css/a-guide-to-flexbox/
您可以使 .typewriter
成为一个绝对定位的元素,并添加通常的居中设置,例如
.typewriter {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
etc.
}