首页 > 解决方案 > flexbox 对齐从中心偏移的项目,没有填充物

问题描述

使弹性项目居中很容易。但是我喜欢将它向上移动一点,这样上下空间之间的关系就是例如 1/2。使用填充物时也很容易。但是有没有办法在没有填充物的情况下做到这一点?HTML:

<div id="filler-top"></div>
<div id="the-item">
</div>
<div id="filler-bottom"></div>

CSS:

    #the-item {
        width: 80vw;
        height: 30vh;
        border: 2px solid lightblue;
      }
      body {
        height: 100vh;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-between;
      }
      #filler-top {
        width: 100%;
        flex: 1;
      }
      #filler-bottom {
        width: 100%;
        flex: 2;
      }

https://jsfiddle.net/Sempervivum/b2wotc8e/3/

应用 margin-top 和 margin-bottom 不起作用,因为百分比是相对于宽度的。

标签: cssflexbox

解决方案


您可以使用伪元素:before,而不是向标记添加 2个元素::after

#the-item {
  width: 80vw;
  height: 30vh;
  border: 2px solid lightblue;
}
body {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}
body:before {
  content: "";
  width: 100%;
  flex: 1;
}
body:after {
  content: "";
  width: 100%;
  flex: 2;
}
<div id="the-item"></div>

另一种选择是简单地使用position:relative,top和的混合transform

#the-item {
  width: 80vw;
  height: 30vh;
  border: 2px solid lightblue;
  position: relative;
  top: 33.333%;
  transform: translateY(-33.333%);
}
body {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}
<div id="the-item"></div>


推荐阅读