Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically centering inside a div with vh [duplicate]

I'm currently trying to center an image inside a div that has it's dimensions set with vh. I tried using the display:table-cell; method which centered the image but began messing with the vw of other elements. I was wondering if there was another simpler way to be vertically centering this image inside a div that as vh. I know this might be a little confusing so hopefully my code down below can help!

Html:

<div class="graphic" style="background-color:#ff837b">
    <img src="images/WAInduo-02.svg" style="width: 100%; height: 50%;" />
</div>

CSS:

#induoIntro .graphic {
    display:block;
    height:100vh;
}
like image 418
kduan Avatar asked Jul 26 '14 15:07

kduan


People also ask

How do I vertically center a div inside a div?

Vertically centering div items inside another div Just set the container to display:table and then the inner items to display:table-cell . Set a height on the container, and then set vertical-align:middle on the inner items. This has broad compatibility back as far as the days of IE9.

How do I vertically center text in a div?

Answer: Use the CSS line-height property Suppose you have a div element with the height of 50px and you have placed some link inside the div that you want to align vertically center. The simplest way to do it is — just apply the line-height property with value equal to the height of div which is 50px .

How do I vertically align an image in the middle of a div?

Answer: Use the CSS vertical-align Property You can align an image vertically center inside a <div> by using the CSS vertical-align property in combination with the display: table-cell; on the containing div element.


1 Answers

It seems that vertical-align:middle has some inconsistency with vw unit. Try positioning approach. Here is the solution for you.

CSS code:

.graphic {
  display: block;
  height: 100vh;
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}

.graphic img {
  vertical-align: middle;
  width: 100%;
  display: inline-block;
  height: 50%;
  position: absolute;
  top: 0;
  bottom: 0%;
  margin: auto;
}

Here is the working fiddle

like image 110
Ashish Balchandani Avatar answered Sep 22 '22 01:09

Ashish Balchandani