Positioning blocks relative to an image

五迷三道 提交于 2019-12-23 23:52:13

问题


I have the following situation:

  • I have a container of a fixed size.
  • Inside the container I display an image (of unknown size) that is bigger than the container. I want to display the image as big as possible (but keeping the aspect ratio). I also want the image to be vertically and horizontally centered in the container (so far so good, I know how do that)
  • Now I want to have two overlays (of unknown size) over the image: one aligned with the top and one with the bottom of the image.

I cannot get the last point right. If it's unclear then hopefully this demo should help: there I have the overlays aligned with top/bottom of the container. Instead I want them aligned with the image. Any help appreciated!


回答1:


position: relative does not work on table cells.

From the spec: http://www.w3.org/TR/CSS21/visuren.html#propdef-position

The effect of 'position:relative' on table-row-group, table-header-group, table-footer-group, table-row, table-column-group, table-column, table-cell, and table-caption elements is undefined.

So, add a wrapper div and apply position: relative to that instead:

http://jsfiddle.net/B9Le8/5/

<div id="container">
    <div> <!-- the wrapper -->
        <img id="img" src="http://lh5.ggpht.com/-J7Q7cUDEFOU/S_bKEoyMSzI/AAAAAAAAGIw/PZJduitsVa0/largeNewGoogleLogoFinalFlat-a.png" />
        <div class="overlay" id="top">Overlay top</div>
        <div class="overlay" id="bottom">Overlay bottom</div>
    </div>
</div>

#container > div {
    position: relative;
}



回答2:


I think you should put the image in a <DIV> and set a style="background:url()" in it. Then in that DIV , put the DIVs that you want to position. It should be easier like that.



来源:https://stackoverflow.com/questions/6712692/positioning-blocks-relative-to-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!