Sebastian Olsen
Sebastian Olsen

Reputation: 10888

Vertically centering div inside parent with viewport height

So I have this div with 100vh - 55px height, and I have a div inside that I want centered vertically inside the parent no matter what. How would I go on about doing this? This is what I have now:

/* home.css | By Seb R | Ekchö */

.lander {
  height: calc(100vh - 55px);
  background: blue;
  overflow: hidden;
}
.lander .content {
  height: 300px;
  margin-top 30vh;
  background: red;
}
<div class="lander">
  <div class="content"></div>
</div>

What am I doing wrong?

Upvotes: 0

Views: 2669

Answers (4)

PrimeCoder
PrimeCoder

Reputation: 21

I just edited the code from above.

.lander .content {
  height: 30vh;
  top: calc((100vh - 30vh) / 2);
  background: red;
  position: relative;
}

You are using px for the hight so css reads it as static size.

Upvotes: 2

PrimeCoder
PrimeCoder

Reputation: 21

You can use this

.lander .content {
background: red none repeat scroll 0 0;
height: 300px;
position: relative;
top: calc((100vh - 300px) / 2);
z-index: 9;

}

or

.lander .content {
background: red none repeat scroll 0 0;
height: 300px;
margin-top: calc((100vh - 300px) / 2);
z-index: 9;

}

Upvotes: 0

Paulie_D
Paulie_D

Reputation: 115288

Simple with absolute positioning.

JSfiddle Demo

.lander {

  height: calc(100vh - 55px);
  background: blue;
  overflow: hidden;
  position: relative;

}

.lander .content {

  height: 300px;
  background: red;
  position: absolute;
  width: 100%;
  left: 0;
  top: 50%;
  margin-top: -150px;  /* half height */

}
<div class="lander">
  <div class="content"></div>
</div>

or Flexbox

JSfiddle Demo

.lander {
    height: calc(100vh - 55px);
    background: blue;
    display:flex;
    flex-direction:column;
    justify-content:center;
}
.lander .content {
    height: 300px;
    background: red;
}
<div class="lander">
    <div class="content"></div>
</div>

Obviously at some point 300px might be larger your assigned viewport (as in the SO snippets) so you may need to adjust before that happens.

Upvotes: 2

Felix A J
Felix A J

Reputation: 6490

There is a : missing in margin-top 30vh;

/* home.css | By Seb R | Ekchö */

.lander {
  height: calc(100vh - 0px);
  background: blue;
  overflow: hidden;
}
.lander .content {
  height: 300px;
  margin-top: 30vh;
  background: red;
}
<div class="lander">
  <div class="content"></div>
</div>

Upvotes: 0

Related Questions