简体   繁体   English

浮动div中的绝对定位图像

[英]absolute positioned image in a floated div

I have a top bar and the links are set using float.In one of the links i have a floated div.In that div i want to show a absolute positioned image.I am using absolute because i do not want to show the full image only a part of it will be displayed.this is achieved by using top and left as 我有一个顶部栏,并使用float设置链接。在其中一个链接我有一个浮动的div.In div我想显示一个绝对定位的图像。我使用绝对,因为我不想显示完整的图像只显示它的一部分。这是通过使用top和left as来实现的

CSS CSS

div.cont{
    max-width:50px;
    min-width:50px;
    height:50px;
    overflow:hidden;
}
img{
    position:absolute;
    width:100px;
    height:100px;
    top:-10px;
    left:-15px;
}

HTML HTML

<div style="float:right;">
    <div class="cont">
        <img src="image url"/>
   </div>
</div>

But as image is absolute positioned it is shown outside that div. 但是,由于图像是绝对定位的,因此它显示在div之外。

How can overcome this and show the image in div? 怎么能克服这个并在div中显示图像?

Thanks in advance. 提前致谢。

Set the position on the parent div: 设置父div的位置:

div.cont{
      max-width:50px;
      min-width:50px;
      height:50px;
      overflow:hidden;
      position:relative;
}

When you position something absolutely, it's positioned relative to the next positioned ancestor. 当你绝对定位时,它相对于下一个定位的祖先定位。 If you don't specify the positioning then the ancestor will be the body. 如果你没有指定定位,那么祖先就是身体。

By default, absolutely positioned elements are positioned relative to the viewport. 默认情况下,绝对定位的元素相对于视口定位。 Add position: relative to your floated div. 添加position: relative对于浮动div。 This will position the image inside relative to its parent, rather than relative to the viewport. 这将相对于其父级而不是相对于视口定位图像内部。

在img上使用margin-topmargin-left而不是left:和top:`。

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

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