我有一个包含 2 个 div
项的 flexbox 容器。 flexbox 容器设置为一行,将内容居中。我正在尝试找出一种方法,使行的内容在第一个元素上居中,然后让第二个元素位于第一个居中元素的右侧。
下面是我最终不得不做的事情:使用 flexbox 将第一个元素居中,然后我必须将第二个元素绝对定位到所需的位置。有没有办法删除第二个元素的绝对定位,让它出现在第一个元素的右侧,居中?
HTML
<div class="center-container">
<div class="time">
<span id="time">00:00</span>
</div>
<div class="time-ampm">
<span id="time-ampm">XX</span>
</div>
</div>
CSS
.center-container {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: center;
}
.time {
flex: 1;
font-size: 50px;
font-weight: 300;
color: #262626;
}
.time-ampm {
position: absolute;
top: 115px;
left: 288px;
/* flex: 1; <= this is what I want to use, not the absolute positioning used above */
font-size: 20px;
font-weight: 400;
color: #858585;
}
如果两个元素都使用 flexbox 设置(不是上面的绝对定位),则此行显示 flexbox 将内容居中的位置
这一行显示了我希望 flexbox 将元素居中的位置(以第一个元素为中心)
最佳答案
将偏移项宽度设置为0怎么样?
HTML:
<div class="container">
<div>12:20</div>
<div class="offset">AM</div>
</div>
和 CSS:
.container {
display:flex;
justify-content: center;
align-items:baseline;
}
.offset {
width:0;
}
关于html - CSS Flexbox 水平居中问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30403651/