1

Centering a flex item is easy. However I like to shift it upwards a bit so that the the relation between the upper and lower space is e. g. 1/2. Easy too when using fillers. But is there a way to do this whithout fillers? 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/

Applying margin-top and margin-bottom doesn't work as a percentage is relative to the width.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Sempervivum
  • 928
  • 1
  • 9
  • 21

1 Answers1

0

instead of adding 2 elements to the markup, you can use :before and :after pseudo-elements:

#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>

Another option is to simply use a mixture of position:relative, top and 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>
Amr Noman
  • 2,597
  • 13
  • 24