gpt4 book ai didi

html - Flexbox:水平和垂直居中

转载 作者:行者123 更新时间:2023-11-28 06:19:39 27 4
gpt4 key购买 nike

如何使用 flexbox 在容器内水平和垂直居中 div。在下面的示例中,我希望每个数字彼此下方(按行),水平居中。

.flex-container {
padding: 0;
margin: 0;
list-style: none;
display: flex;
align-items: center;
justify-content: center;
}
row {
width: 100%;
}
.flex-item {
background: tomato;
padding: 5px;
width: 200px;
height: 150px;
margin: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
}
<div class="flex-container">
<div class="row">
<span class="flex-item">1</span>
</div>
<div class="row">
<span class="flex-item">2</span>
</div>
<div class="row">
<span class="flex-item">3</span>
</div>
<div class="row">
<span class="flex-item">4</span>
</div>
</div>

http://codepen.io/anon/pen/zLxBo

最佳答案

我想你想要像下面这样的东西。

html, body {
height: 100%;
}
body {
margin: 0;
}
.flex-container {
height: 100%;
padding: 0;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
}
.row {
width: auto;
border: 1px solid blue;
}
.flex-item {
background-color: tomato;
padding: 5px;
width: 20px;
height: 20px;
margin: 10px;
line-height: 20px;
color: white;
font-weight: bold;
font-size: 2em;
text-align: center;
}
<div class="flex-container">
<div class="row">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
<div class="flex-item">4</div>
</div>
</div>

参见演示:http://jsfiddle.net/audetwebdesign/tFscL/

如果你想要高度和顶部/底部填充,你的 .flex-item 元素应该是 block 级的(div 而不是 span)才能正常工作。

此外,在 .row 上,将宽度设置为 auto 而不是 100%

您的 .flex-container 属性没问题。

如果您希望 .row 在视口(viewport)中垂直居中,请将 100% 高度分配给 htmlbody,并且将 body 边距清零。

注意.flex-container需要一个高度才能看到垂直对齐效果,否则容器会计算围住内容需要的最小高度,这个高度小于视口(viewport)高度示例。

脚注:
flex-flowflex-directionflex-wrap 属性可以使此设计更易于实现。我认为不需要 .row 容器,除非您想在元素周围添加一些样式(背景图像、边框等)。

有用的资源是:http://demo.agektmr.com/flexbox/

关于html - Flexbox:水平和垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35682498/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com