简体   繁体   中英

Position child elements in Container

I am trying this: there is a picture element Which is wrapped inside a container div

<div id="container">
    <div id="a">
        <img src="b.jpg" alt="b" />
    </div>
</div>

Now I want to place the child elements such a way that the top and left of the picture is always 25% of the height & width of the container div. How can I achieve this?

If that is the only requirement, you can just do it by adding a padding on the inner div.

According to W3C, it those percentages should refer to the dimensions of the outer div.

Like margin properties, percentage values for padding properties refer to the width of the generated box's containing block

http://www.w3.org/TR/CSS2/box.html

For the height, it will only work if your inner div is the only element inside your outer div (because the inner div will determine the height of the other). So for you example, it'll work.

Try this:

#container {position: relative;}
#container #a {position: absolute; left: 25%; top: 25%;}

Here's a working fiddle: jsFiddle

Try:

#container { position:relative; }
#container img { position:absolute; top:25%; left:25%; }

Live demo: jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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