简体   繁体   English

CSS流体图像问题…垂直对齐和图像不在div的顶部开始

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

JS FIDDLE Example http://jsfiddle.net/2adv2/ JS FIDDLE示例 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. 当图像宽度为最大宽度时,如果我调整大小以增加窗口高度,则图像不会移至div的中间,但div会扩大。

I am facing 2 issues 我面临2个问题

  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. 当我调整窗口大小时,图像会从div向下移动一点,并且有点溢出-垂直挤压网页。

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. 恐怕您不能使用vertical-align将容器中的东西垂直居中。

However, you can use display:table and display:table-cell with vertical-align:middle to work as you are expecting. 但是,可以将display:tabledisplay:table-cellvertical-align:middle一起使用,以达到预期的效果。

This requires two wrapping div tags around the image that you want to center. 这需要在要居中的图像周围包裹两个div标签。

The following illustrates the basic technique: 下面说明了基本技术:

CSS: 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: 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/ 请参见将这种技术应用于您的示例的小提琴: http : //jsfiddle.net/2adv2/1/

add max-height to the #hero so the div resizes together with the img 将max-height添加到#hero中,以便div和img一起调整大小

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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