CSS弹性盒子水平居中问题

3
我有一个flexbox容器,其中包含2个div项。该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居中项目的位置(以第一个项目为中心)。

期望中心


只是一个反思。你想让你的项目增长 (flex-grow > 0) 吗?如果是这样,项目将占据容器的全部空间,没有必要说 am 文本必须在其他项目旁边...或者我理解错了什么? - vals
1个回答

3

关于将偏移项目的宽度设置为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;
}

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接