如何在两个div之间定位一张图片

6
我需要在两个div底部之间定位一张图片,其中一个div在另一个div内,如下图所示: example 这个例子的代码如下:
<div style="background:blue;width:500px;height:150px;overflow:hidden;">
   <div style="background:red;width:500px;height:100px;margin-top:20px;">
    //DOES IMAGE GOES HERE?
   </div>   
</div>

我知道可以使用绝对定位来对图像进行定位,但我不喜欢这种方式。还有其他的方法吗?谢谢!
6个回答

5

嘿,现在已经习惯了这个。

.parent{
background:blue;
  width:500px;
  height:150px;
  overflow:hidden;
}
.child{
background:red;
  width:500px;
  height:100px;
  margin-top:20px;
  position:relative;
}
.child img{
position:absolute;
  bottom:-25px;
  right:6%;
  width:200px;
  height:50px;
}

.parent{
background:blue;
  width:500px;
  height:150px;
  overflow:hidden;
}
.child{
background:red;
  width:500px;
  height:100px;
  margin-top:20px;
  position:relative;
}
.child img{
position:absolute;
  bottom:-25px;
  right:6%;
  width:200px;
  height:50px;
}
<div class="parent">
   <div class="child">
    <img src="http://fakeimg.pl/250x100/">
   </div>   
</div>


它工作得很好!!!我将底部编辑为0像素,所以它在两个div之间居中..但是..(我正在使用13英寸的屏幕尺寸)如果我在一个更大的屏幕上看呢?可以吗? - Jayyrus

1

完整的CSS示例

.blue {
  background: blue;
  width: 500px;
  height: 150px;
  overflow: hidden;
}

.red {
  background: red;
  width: 500px;
  height: 100px;
  margin-top: 20px;
  position: relative;
}

.image {
  position: absolute;
  bottom: -10px;
  /* half of image height */
  right: 10px;
  /* right space */
}

.image img {
  display: block;
  width: 100px;
  height: 20px;
  background: green;
}
<div class="blue">
  <div class="red">
    <div class="image">
      <img src="" alt="" />
    </div>
  </div>
</div>


0

试试这个:

<div style="background:blue;width:500px;height:150px;overflow:hidden;">
   <div style="background:red;width:500px;height:100px;margin-top:20px; 
               padding-left: 250px ; padding-top: 50px">
    //IMAGE GOES HERE.
   </div>   
</div>

填充可以帮助留出空间。


我在内部div中有其他元素。 - Jayyrus
如果您在内部div中有其他元素,请共享标记结构,以便我们找到适当的标记,其中可以放置img标记。 - Ravi Jain

0
最好的是:

HTML

<div style="background:blue;width:500px;height:150px;overflow:hidden;">
   <div style="background:red;width:500px;height:100px;margin-top:20px;position:relative;">
    <img src="" style="position:absolute;bottom:-10px;" />
   </div>   
</div>

我已经添加了绝对定位。

JSFIDDLE


0
您可以尝试以下代码。
<div style="background:blue;width:500px;height:150px;overflow:hidden;">
   <div style="background:red;width:500px;height:100px;margin-top:20px;">
   </div>   
   <img src="imageNemaHere" width="134" height="28" style="float:right; margin:-10px 10px 0 0" />
</div>

0

关于 position:relative 呢?

<div style="background:blue;width:500px;height:150px;overflow:hidden;">
   <div style="background:red;width:500px;height:100px;margin-top:20px;">
    <img src="http://placehold.it/80x40" style="position:relative;left:400px;top:80px">
   </div>   
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

http://jsfiddle.net/ABEne/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接