【问题标题】:Why does align: center in the parent mess up my position: absolute overlays?为什么 align: center in parent 会弄乱我的位置:绝对叠加?
【发布时间】:2018-09-02 17:25:25
【问题描述】:

有人能解释一下为什么在这个菜单的父级中使用display: flex; align: center; 会弄乱子元素中的两个绝对定位的叠加层吗?

这是一个小提琴,您可以在其中尝试使用和不使用align: center 来理解我的意思。 (取消注释 /* 对齐:居中;*/ 在 .menu 中)

https://jsfiddle.net/Hastig/wmtr87gc/

body { background-color: gray;}
.menu {
    display: flex;
    justify-content: center;
    /* align-items: center; */
    width: 100%;
    padding: 5px 0;
    background-color: hsl(0, 0%, 30%);
}
.menu-item {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
  font-size: 13px;
  color: hsl(0, 0%, 70%);
}
.menu-item.progress {
  background-color: gray;
}
.progress-bar {
  position: absolute;
  top: 0; bottom: 0; left: 0;
  width: 83%;
  background-color: hsla(191, 58%, 46%, 1);
}
.progress-value {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
  color: hsl(0, 0%, 90%);
}
<div class="menu">
  <div class="menu-item">Stuff</div>
  <div class="menu-item progress">
    <div class="progress-bar"></div>
    <div class="progress-value">83</div>
  </div>
  <div class="menu-item">Things</div>
</div>

【问题讨论】:

    标签: css flexbox css-position


    【解决方案1】:

    因为中间元素只包含绝对元素,所以它内部没有流入内容来定义它的高度。然后默认的align-itemsstretch,所以你的元素默认会被拉伸,它的高度将等于它的父高度但是如果你改变对齐,元素会考虑它的内容来定义高度,因为没有 in- flow 元素将具有height:0,这意味着由top:0;bottom:0 定义的进度条也将具有高度0

    为避免这种情况,请至少保留一个未定位的元素(包含文本的元素),以便中间元素具有一些流入内容,并且其高度将不同于 0 不管对齐方式是.

    body {
      background-color: gray;
    }
    
    .menu {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      padding: 5px 0;
      background-color: hsl(0, 0%, 30%);
    }
    
    .menu-item {
      position: relative;
      z-index:0;
      display: flex;
      justify-content: center;
      align-items: center;
      flex: 1;
      font-size: 13px;
      color: hsl(0, 0%, 70%);
    }
    
    .menu-item.progress {
      background-color: gray;
    }
    
    .progress-bar {
      position: absolute;
      z-index:-1;
      top: 0;
      bottom: 0;
      left: 0;
      width: 83%;
      background-color: hsla(191, 58%, 46%, 1);
    }
    
    .progress-value {
      color: hsl(0, 0%, 90%);
    }
    <div class="menu">
      <div class="menu-item">Stuff</div>
      <div class="menu-item progress">
        <div class="progress-bar"></div>
        <div class="progress-value">83</div>
      </div>
      <div class="menu-item">Things</div>
    </div>

    【讨论】:

    • 感谢您的解释。 50k 快乐。
    猜你喜欢
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    相关资源
    最近更新 更多