flexbox - 1/3 和 2/3 比例的中心项目

新手上路,请多包涵

我需要将项目(一个)居中放置在 13 行空间中,并将另一个项目(两个)居中放置在行空间的其余部分(2/3)中。

https://jsfiddle.net/gpe9a5qb/1/

如何将项目居中到它们适合的特定空间,这样它们就不会居中取决于它们的大小,而是取决于它们签名的空间大小(1/3 和 2/3)?

 body {
  border: 1px dotted yellow;
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  background: brown;
}

.container {
  background: red;
  width: 250px;
  height: 100px;
}

.box {
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.one {
  background: green;
  flex: 1 1 auto;
}

.two {
  background: blue;
  flex: 2 1 auto;
}
 <div class="container">
  <div class="box">
    <div class="one">1/3</div>
    <div class="two">2/3</div>
  </div>
</div>

.one 应该在 13 空间内居中,而 .two 必须在 23 空间内居中。

原文由 yasiDrovi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 245
2 个回答

如果我没听错,你说的是水平居中。

CSS 看起来像这样

body
{border:1px dotted yellow;
margin:0;
padding:0;
width:100%;
height:100%;
background:brown;}

.container{
background:red;
width:250px;
height:100px;}

.box
{display:flex;
}
.box > div{
  display:flex;
  justify-content:center;
}

.one
{
 background:green;
flex-basis:33.33%;
}

.two
{background:blue;
flex-basis:66.66%;}

希望这可以帮助。

我在这里所做的是,我将 flex 放在内部 div 上,并将它们的内容居中(而不是父容器,你不能居中,因为它们占用了空间)。

原文由 Daniel Kormos 发布,翻译遵循 CC BY-SA 4.0 许可协议

你快到了。只需要一个修改:

使用 justify-content: center 使每个弹性项目成为弹性容器。

而已。

 .container {
  background: red;
  width: 250px;
  height: 100px;
}

.box {
  display: flex;
  align-items: center;
  /* justify-content: space-around */ /* remove; doing nothing */
}

.one {
  background: green;
  flex: 1 1 auto;

  /* NEW */
  display: flex;
  justify-content: center;
}

.two {
  background: blue;
  flex: 2 1 auto;

  /* NEW */
  display: flex;
  justify-content: center;
}

body {
  border: 1px dotted yellow;
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  background: brown;
}
 <div class="container">
  <div class="box">
    <div class="one">1/3</div>
    <div class="two">2/3</div>
  </div>
</div>

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题