html - CSS Flexbox 水平居中问题

标签 html css flexbox

我有一个包含 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 将内容居中的位置

current center

这一行显示了我希望 flexbox 将元素居中的位置(以第一个元素为中心)

desired center

最佳答案

将偏移项宽度设置为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

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

相关文章:

javascript - 在悬停时使用 jquery 显示具有向下滚动效果的隐藏 div

javascript - AngularJS - 如何为自定义指令设置 css 类?

html - 网页部分的半透明效果

html - Flex 使用 justify-content

html - 粘性 Flexbox 页脚不起作用

html - 将带有线框的 3D 表面从 R 导出到 HTML

html - ckeditor 和 codesnippets 插件

php - HTML5 - 共享主机中的 WebSocket

php - 将下拉菜单的值传递给另一个页面

html - 使用CSS设计名片的难度