Evanss
Evanss

Reputation: 23543

Vertically center an element on the page with CSS?

I need to vertically centre an element of unknown height on a page.

I can vertically center it relative to a containing div with this:

.one {
  background: grey;
  width: 50%;
  position: relative;
  top: 50%; 
 transform: translateY(-50%); 
  margin: auto;
}
.cont {
  background: blue;
  height: 300px;
}

http://codepen.io/anon/pen/lfrJx

However I cant get it to center vertically on the page:

.one {
  background: grey;
  width: 50%;
  position: relative;
  top: 50%; 
 transform: translateY(-50%); 
  margin: auto;
}
.cont {
  background: blue;
  height: 100%;
}

http://codepen.io/anon/pen/gqLcB

Upvotes: 0

Views: 82

Answers (2)

Samer Allahham
Samer Allahham

Reputation: 76

put this css :)

.one {
  background: grey;
  width: 50%;
  position: relative;
  margin-top:auto;
  margin-bottom:auto;
  vertical-align:middle;
}
.cont {
display: table-cell;
  background: blue;
  width:100%;
}

Upvotes: 1

Favitalegur
Favitalegur

Reputation: 36

http://codepen.io/anon/pen/mFGeH

.cont {
  position:absolute;
  background: blue;
  height: 100%;
  width:100%;
}

Upvotes: 0

Related Questions