Xtian
Xtian

Reputation: 3587

2 Relative Positioned Divs?

I have a container div that has relative positioning, then another div inside that also has relative positioning:

<div class="first">
  <div class="second">
    <img src="img.jpg" />
  </div>
</div>

I would like an image with absolute positioning to be relative to the "second" div not the "first". But I need them both to have relative positioning, how do I specify so the image is relative to the "second" div?

Upvotes: 2

Views: 273

Answers (3)

Aaron Bennett
Aaron Bennett

Reputation: 3944

In the page hierarchy the image would be relative to .second; however, you must define the parent to be relatively positioned for the child to care.

see: http://css-tricks.com/absolute-positioning-inside-relative-positioning/

.second { position:relative; }
.second img { position:absolute; top:0; left: 0 }

Upvotes: 3

davin
davin

Reputation: 45525

It is relative to the second <div> automatically according to the CSS standards, since it is nested in the second <div> and that div is positioned. Here is a quote from the CSS2 standard:

The containing block for a positioned box is established by the nearest positioned ancestor

So you count upwards in the DOM tree, i.e. from the nearest ancestor towards the document root, and stop at the first positioned ancestor (and if there isn't one, then it's the closest container, but that doesn't apply here). In this case, that will be div.second like you want.

Upvotes: 1

billy
billy

Reputation: 41

.second img{ position:absolute; top:0; left:0; }

The positioning is just an example; you can change it to suit your needs.

Upvotes: 0

Related Questions