Flexbox的。对齐项目中心而不是忽略填充

时间:2017-06-14 13:50:10

标签: html css css3 flexbox

如何让flex孩子不与顶部填充重叠?

在此示例中,子.large居中,但由于其较大的高度,其顶部位于其父级的顶部边界上方。有没有办法防止这种情况,并使.large在没有JS的.flex填充顶部之后? flex-start将是不好的解决方案,因为.flex内的块可能具有较小的高度,并且必须位于.flex的中心。 .flex必须定位为absolutefixed

https://jsfiddle.net/zoxamy9f/1/



.large {
  background: red;
  height: 200%;
  flex: 1;
}

html, body {
  height: 100%;
  overflow: hidden;
}

.flex {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  padding-top: 10%;
  height: 100%;
  background: black;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: auto;
}

<div class="flex">
  <div class="large"></div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

你是否有可能将你的结构改变成这样的东西?

.large {
  background: red;
  height: 200%;
  flex: 1;
}

html,
body {
  height: 100%;
  overflow: hidden;
}

.wrap {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: black;
}

.flex {
  width: 100%;
  height: 100%;
  margin-top: 10%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}
<div class="wrap">
  <div class="flex">
    <div class="large"></div>
  </div>
</div>

答案 1 :(得分:1)

如果您在flexlarge之间添加包装,则可以完成

我还使用了视口单元vh而不是%,因为百分比无法启用垂直居中。

Fiddle demo

Stack snippet - 内容很多

.wrapper {
  display: inline-flex;
  flex-direction: column;
  width: 100%;
  height: calc(100% - 10vh);
  justify-content: center;
}
.large {
  background: red;
  width: 100%;
}
.flex {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  padding-top: 10vh;
  height: 100%;
  background: black;
  overflow: auto;
  box-sizing: border-box;
}
<div class="flex">
  <div class="wrapper">
    <div class="large">
      Content 1
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
      <br> Content
    </div>
  </div>
</div>

Stack snippet - 内容很少

.wrapper {
  display: inline-flex;
  flex-direction: column;
  width: 100%;
  height: calc(100% - 10vh);
  justify-content: center;
}
.large {
  background: red;
  width: 100%;
}
.flex {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  padding-top: 10vh;
  height: 100%;
  background: black;
  overflow: auto;
  box-sizing: border-box;
}
<div class="flex">
  <div class="wrapper">
    <div class="large">
      Content 1
      <br> Content
      <br> Content
      <br> Content
    </div>
  </div>
</div>