将 <span> 相对于容器 div 居中,将另一个跨度与其左侧的右对齐文本对齐

Center a <span> relative to container div, align another span with right-aligned text left of it

我正在尝试将一个 span 元素对齐到容器 div 的中心,并让另一个 span 的文本右对齐到它的左侧:

+--------------------------------------------------------+
| <div>                                                  |
+----------------------+----------+                      |
| <span>               | <span>   |                      |
|                      |          |                      |
|                      |          |                      |
|                      |          |                      |
|        right-aligned | centered |                      |
|                      |          |                      |
|                      |          |                      |
|                      |          |                      |
|                      |          |                      |
+----------------------+----------+                      |
|                                                        |
+--------------------------------------------------------+

两个 span 的内容都是动态生成的,所以我想尽可能避免任何绝对像素宽度。

知道如何实现这种布局吗?

这是我根据 Persinj 的回答最终使用的标记:

HTML

<nav class="navbar">
  <span class="nav-aside">Right-aligned:&nbsp;</span>
  <span class="nav-menu">centered</span>
  <span class="nav-aside"></span>
</nav>

CSS

nav.navbar {
  display: flex;
}
span.nav-aside {
  flex-grow: 1;
  flex-basis: 0;
  text-align: right;
}
span.nav-menu {
  align-self: center;
  text-align: center;
}

由于我对浏览器的要求有限,因此我将供应商前缀排除在我的标记之外,并且我依靠 autoprefixer 来处理这个问题。如果需要,请查看已接受的答案。

HTML:

<div class="wrapper">
  <span class="span-left">right-aligned</span>
  <span class="span-center">centered</span>
</div>

CSS:

.span-left, .span-center { display: inline-block; }

.span-left {
  width: 40%;
  text-align: right;
}

.span-center {
  width: 20%;
  text-align: center;
}

或者,在您的跨度上使用 display: blockfloat: left;(不要忘记在包装器之后清除)。

Flexbox 设计/布局

这可以使用 flex 解决:

设置树框: 在旁边,中心和一个隐藏的,将填充所需的space。
设置 flex-grow 将使它们占据页面的不同部分。
对每个设置 flex-grow: 1; 将使它们占用相等 space。 将其中之一设置为 flex-grow: 0.5;将减少这部分 space 的增长。
添加带有 flex 属性 的包装器,我们可以使用 align-items:center 来确保它们位于包装器的中心。

Fiddle

.wrapper {
  height: 250px;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-flow: row wrap;
  flex-wrap: nowrap;
  flex-direction: row;
  align-items: center;
  text-align: center;
}

.center,
.aside,
.not-shown {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
}

.center {
  flex-grow: 0.5;
  background-color: lightblue;
  height: 50px;
}

.aside {
  text-align: right;
  background-color: 1;
  background: lightgreen;
  height: 50px;
}

.not-shown {
  visibility: hidden;
  flex-grow: 1.5;
  height: 50px;
}
<div class="wrapper">
  <div class="aside">
    aside
  </div>
  <div class="center">
    center
  </div>
  <div class="not-shown">
  </div>
</div>