【问题标题】:Pin one child in center with flexbox用 flexbox 将一个孩子固定在中心
【发布时间】:2019-01-10 11:46:40
【问题描述】:

我正在尝试将每个“父”的“子特征”与带有 flexbox 的“容器”类的中心对齐。

这就是我现在拥有的:

这是所需的输出:

这可能吗?

.parent {
  display: flex;
  align-items: flex-start;
  height: 100%;
  border-color: #3B8686;
  justify-content: center;
  margin-bottom: 1em;
  position: relative;
  z-index: 2;
}

.child {
  background-color: #79BD9A;
  border-color: #CFF09E;
  padding: 1em;
  text-align: center;
  margin: 0 0.1em
}

.child--featured {
  background-color: #3B8686;
}

.parent.one .child {
  width: 3em
}

.parent.one .child:nth-child(1) {
  width: 8em
}

.parent.one .child:nth-child(4) {
  width: 6em
}

.parent.two .child {
  width: 4em;
}

.parent.two .child:nth-child(1) {
  width: 1em
}

.parent.two .child:nth-child(2) {
  width: 5em
}

.parent.two .child:nth-child(3) {
  width: 6em
}

.parent.two .child:nth-child(4) {
  width: 5em
}

.parent.three .child {
  width: 2em
}

.parent.three .child:nth-child(4) {
  width: 5em
}

.parent.three .child:nth-child(3) {
  width: 2em
}

.parent.three .child:nth-child(2) {
  width: 10em
}

.parent.three .child:nth-child(1) {
  width: 10em
}

.rule {
  position: absolute;
  left: 50%;
  top: 0;
  height: 100%;
  width: 2px;
  background: #333;
  z-index: 1;
}
<div class="container">

  <p class="rule"></p>

  <div class="parent one">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child child--featured">3</div>
    <div class="child">4</div>
    <div class="child">5</div>
  </div>

  <div class="parent two">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child child--featured">3</div>
    <div class="child">4</div>
    <div class="child">5</div>
  </div>

  <div class="parent three">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child child--featured">3</div>
    <div class="child">4</div>
    <div class="child">5</div>
  </div>
  
</div>

Codepen

【问题讨论】:

  • 没有这些图片,这个问题很难解释。我试图弄清楚如何在没有图像的情况下编写问题。该死的,我正要离开我的电脑过夜。
  • 如何将不同长度的各行对齐到容器的中心,由每行中的指定元素锚定?
  • 那比我的好。
  • 那你需要知道“3”在行中的位置,这样才能确定position的偏移值。
  • 就像我说的,CSS 在这里可能不是您的最佳选择。可能有更清洁、更高效的 JS 解决方案。

标签: html css flexbox


【解决方案1】:

是的,这是可能的。我已经试过了,我的头已经出来了。但我已经做到了。你可以这样:

.parent.one {
     margin-left: -30px;
}
.parent.two {
    margin-left: 50px;
}
.parent.three {
    margin-left: -200px;
}

【讨论】:

  • 我不能为边距设置固定值,因为这些行将动态生成,每个子项的宽度都不同。
  • 所以,我不能用其他方式做到这一点:(
  • 没关系。感谢您的努力。 :)
猜你喜欢
  • 2015-10-05
  • 2017-12-12
  • 2019-07-31
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多