0

I have searched here but can't seem to find a solution for my problem due to the dynamic nature of the divs.

For my site I want a banner image that will scale down as a cheap kinda responsiveness. I have that part down pat, I just cannot get my image to center vertically. I have created a jsFiddle and the code is below.

HTML

<div class="banner col-lg-12">
    <img src="http://laurentvandessel.be/wp-content/uploads/2014/03/placeholder.png" /> 
</div>

CSS

.banner {
    margin-top: 51px;
    margin-bottom: 20px;
    overflow:hidden;
    text-align: center;
    height:300px;
    display: inline-block;
    vertical-align: middle;
}

.banner img {
    position:relative;
    width:100%;
    left: 100%;
    margin-left: -200%;
    display:inline-block;
    vertical-align: middle;
}

Also, if you have a better way of doing what I'm already doing that would be appreciated as well.

Thanks heaps guys.

Joshua
  • 1,128
  • 3
  • 17
  • 31
  • 1
    Check out this answer: http://stackoverflow.com/questions/18516317/vertically-align-an-image-inside-a-div-with-responsive-height/18516474#18516474 – Muhammad Osmond Jun 19 '14 at 06:45

3 Answers3

1

It's a little tricky, because sometimes the image is taller than the container. You could do it like this, though (see the last three lines):

.banner img {
  position:relative;
  width:100%;
  left: 100%;
  margin-left: -200%;
  display:inline-block;
  vertical-align: middle;
  top: 50%;
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
}

If that suits, you might as well use this method for horizontal centering too:

.banner img {
  position:relative;
  width:100%;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
ralph.m
  • 13,468
  • 3
  • 23
  • 30
0


Do you need dynamical div Height for img with dynamical height! set your css

.banner{height:auto; ...}

if you need a center vertically and also Horizontally div for TEXT and also images you can look on my jsFiddle test.

H.Rafiee
  • 358
  • 1
  • 9
0

Demo

css

.banner {
    margin-top: 51px;
    margin-bottom: 20px;
    /*overflow:hidden;
    text-align: center;*/
    height:300px;
    /*display: inline-block;
    vertical-align: middle;*/
    background: url(http://laurentvandessel.be/wp-content/uploads/2014/03/placeholder.png) no-repeat center center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
/*.banner img {
    position:relative;
    width:100%;
    left: 100%;
    margin-left: -200%;
    display:inline-block;
    vertical-align: middle;
}*/

html

<div class="banner col-lg-12">
    <!--<img src="http://laurentvandessel.be/wp-content/uploads/2014/03/placeholder.png" />-->
</div>
4dgaurav
  • 11,360
  • 4
  • 32
  • 59