absolute positioned image in a floated div

19,499

Solution 1

Set the position on the parent 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.

Solution 2

By default, absolutely positioned elements are positioned relative to the viewport. Add position: relative to your floated div. This will position the image inside relative to its parent, rather than relative to the viewport.

Share:
19,499
harikrishnan.n0077
Author by

harikrishnan.n0077

Updated on June 04, 2022

Comments

  • harikrishnan.n0077
    harikrishnan.n0077 about 2 years

    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

    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

    <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.

    How can overcome this and show the image in div?

    Thanks in advance.