在 css 中将图像定位在 div 下

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11932100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 04:47:19  来源:igfitidea点击:

Positioning image under div in css

csspositioning

提问by Dreamwalker

I've got a question regarding positioning of two objects: image and div. I want bg2.png image to stay under div.I keep encountering problem with image pushing div down by img's height. How do I avoid that?

我有一个关于定位两个对象的问题:图像和 div。我希望 bg2.png 图像留在 div 下。我一直遇到图像按 img 的高度向下推 div 的问题。我该如何避免?

I tried pushing down image with "top:" value but of course it leaves me with empty area above div. Also I tried adding negative "top:" value and relative position to "maincontent" div but again it left me with empty area, only difference was that this time it was under the div.

我尝试使用“顶部:”值向下推图像,但当然它会在 div 上方留下空白区域。我还尝试向“maincontent”div 添加负的“top:”值和相对位置,但它再次给我留下了空白区域,唯一的区别是这次它在 div 下。

HTML:

HTML:

<body>
 <img src="./images/bg2.png" class="bgimg" />
 <div id="maincontent">
 </div>
</body>

CSS:

CSS:

body {
    width: 100%;
    background: #000;
}
.bgimg {
    z-index: -1;
    overflow: hidden;
    left: 70px;
    position: relative;
    display: block;
}
#maincontent {
    height: 520px;
    width: 960px;
    margin: 20px auto;
    display: block;
    z-index: 8;
}

Thanks in advance.

提前致谢。

edit - what I'm trying to achieve: Click me!

编辑 - 我想要实现的目标: 点击我!

回答by Mark

2 solutions:

2个解决方案:

Change your HTML structure:

改变你的 HTML 结构:

<body>
 <div id="maincontent">
 </div>
 <img src="./images/bg2.png" class="bgimg" alt="some">
</body>

or make it as the background-image:

或将其作为背景图像:

<body>
  <div id="maincontent">
  </div>
</body>

#maincontent {
 background: url(./images/bg2.png) no-repeat 0 100%;
 padding-bottom: height_of_image_in_px;
}

回答by Anooj P

<style>
body {
    width: 100%;
    background: #000;
}
.bgimg {
    z-index: -1;
    overflow: hidden;
    left: 70px;
    position: relative;
    display: block;
}
#maincontent {
    height: 520px;
    width: 960px;
    margin: 20px auto;
    display: block;
    z-index: 8;
}

</style>

<body>

 <div id="maincontent">
     <img src="./images/bg2.png" class="bgimg" alt="some info about image here">
 </div>
</body>

if you want that image inside the div use this code. or if you want make that image background of that div use css background property

如果您希望在 div 中使用该图像,请使用此代码。或者如果你想让那个 div 的图像背景使用 css background 属性