Rotan
Rotan

Reputation: 597

CSS positioning relative to div

I have two images inside a div. I'd like to position these images using percent relatively to the parent div.

Here's a fiddle to understand: http://jsfiddle.net/b9ce626s/

I tried to set position: absolute; on the image but it uses window width.

I need the image on the very right be positioned at 95% of the red div, and not the window. I also don't want the left image impacts the positionning of the right one.

Upvotes: 1

Views: 81

Answers (4)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

Add position: relative on #main so the position of the images are both based on that element (and not on the root element). Example: http://jsfiddle.net/b9ce626s/1/

A page element with relative positioning gives you the control to absolutely position children elements inside of it.

https://css-tricks.com/absolute-positioning-inside-relative-positioning/

As a side note, if you assign a width with a percentage value to the images, it will be now based on the parent element width.

Upvotes: 3

Jacob G
Jacob G

Reputation: 14152

Give main position: relative; like so:

#main {
  display: block;
  width: 50%;
  height: 50%;
  background-color: red;
  position:relative;
}

This keyword lays out all elements as though the element were not positioned, and then adjust the element's position, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned). The effect of position:relative on table-*-group, table-row, table-column, table-cell, and table-caption elements is undefined.

JSFiddle Demo

Upvotes: 0

Jakir Hossain
Jakir Hossain

Reputation: 2517

 #main {
            display: block;
            width: 50%;
            height: 50%;
            background-color: red;
            position: relative;
        }

Upvotes: 0

Aru
Aru

Reputation: 1870

Try this..

Html

<div id="main">
    <img id="card1" src="http://dynamic-projets.fr/wp-content/uploads/2012/08/attach_image.png" alt="KH" />
    <img id="card2" src="http://www.rotaryd1650.org/images/main/IconesCollectionPro/128x128/image_gimp.png" alt="9H" />
</div>

Css

body, html {
            width: 100%;
            height: 100%;
            margin: 0;
        }
        #main {
            display: block;
            width: 50%;
            height: 50%;
            background-color: red;
            position:relative;
        }
        img {
            position: absolute;
            width: 5%;
        }
        #card1 {
            left:5%;
        }
        #card2 {
            right: 5%;
        }

Fiddle Sample

Upvotes: 1

Related Questions