简体   繁体   中英

CSS Fluid image issue… Vertical Align & Image not starting at the top of the div

JS FIDDLE Example http://jsfiddle.net/2adv2/

Update on Vertical Align

Vertical Align works until the max-width is not reached. When the image width is at max width, and if I resize to increase the window height, the image doesn't shift to the middle of the div, but the div expands.

I am facing 2 issues

  1. Vertical align is not happening

  2. The image moves down a little from the div and kinda overflows when I resize the window a lot - squishing the webpage vertically.

Tell me why this happens. Also vertical align just wont work.

CSS:

#heroimg {
    position:relative;
    top:0%;
    height:auto;
    vertical-align:middle;
    max-height:100%;
    max-width:100%;

}

#hero {
    position:relative;
    top:0%;
    bottom:40%;
    height:40%;
    text-align:center;
    overflow:hidden;
    background-color:yellow;
}

HTML:
<div id='hero'><img id="heroimg" src="assets/images/dfb.jpg"></div>

I'm afraid you can't use vertical-align to vertically center things in containers.

However, you can use display:table and display:table-cell with vertical-align:middle to work as you are expecting.

This requires two wrapping div tags around the image that you want to center.

The following illustrates the basic technique:

CSS:

#outer-wrapper {
  display: table;
  width: 100%;
}
#inner-wrapper {
  display: table-cell;
  vertical-align: middle;
}
img {
  margin: 0 auto;
  max-width: 100%;
  height: auto;
}

HTML:

<div id="outer-wrapper">
  <div id="inner-wrapper">
    <img src="image.jpg">
  </div>
</div>

See fiddle with this technique applied to your example: http://jsfiddle.net/2adv2/1/

add max-height to the #hero so the div resizes together with the img

#hero {
    position:relative;
    top:0%;
    bottom:40%;
    max-height:40%;
    text-align:center;
    overflow:hidden;
    background-color:yellow;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM