0

I have an img if I give it a width:100%; and no height. When the window change, the width adapts to its parent and the height keeps the proportion. Can I make a div behave the same way?

For different reasons, I need the div be the width and height than the img. In this case, the img original size is 600 x 300 px.

The example here to play: http://jsfiddle.net/r05zpdd0/

HTML:

<img src="http://www.w3.org/html/logo/downloads/HTML5_sticker.png"/>
<div id="nota">some text</div> 

CSS:

img {
    position:relative;
    margin:0 auto;
    width:100%;
}

div {
    position:relative;
    margin:0 auto;
    width:100%;

    text-align: center;
    display: inline-block;
    background: blue;
}
Nrc
  • 9,577
  • 17
  • 67
  • 114
  • A div does behave the same way, with the exception that its contents does not scale when the parent is resized. Are you asking for a way to keep the aspect-ratio of a div at a certain relationship? – shennan Nov 13 '15 at 15:59
  • @shennan yep he is, there's already a post on it so I linked to it in my answer :) – SidOfc Nov 13 '15 at 16:00
  • 1
    Like this http://jsfiddle.net/j08691/r05zpdd0/1/? – j08691 Nov 13 '15 at 16:01
  • I am sorry, now I see my question is a duplicate. What should I do now? – Nrc Nov 13 '15 at 16:38
  • @Nrc don't worry, you can leave your post like this, it will act as a pointer to the "main" one. – web-tiki Nov 13 '15 at 16:41

1 Answers1

1

You certainly can. CSS:

    img {
        position:relative;
        margin:0 auto;
        width:100%;
    }

    div.wrap{
        position:relative;
        margin:0 auto;
        width:100%;
        padding-top:50%;
        text-align: center;
        display: block;
        background: blue;
    }

    div#nota
    {
        position:absolute;
        top:0;
    }

HTML:

<img src="http://www.w3.org/html/logo/downloads/HTML5_sticker.png"/>
<div class="wrap">
    <div id="nota">some text</div>
</div>

Jsfiddle: http://jsfiddle.net/nfvksydp/

So I had to create a wrapper around your #nota div which is positioned relative. This allows the #nota div to be positioned absolutely within this div. The wrap div has a padding-top of 50% meaning that the height of the div will always be 50% that of the width.

Darren Gourley
  • 1,798
  • 11
  • 11