Seong Lee
Seong Lee

Reputation: 10520

:first-child, :last-child not working

I have a graphic element that I want to position on top of another element. Because I do not want to create css selectors for those that have no re-use, I have applied psuedo class. :first-element that is supposed to sit on top of the other is hidden by the other element.

Here is my JS BIN

HTML

<div class="wrapper">
    <div></div>
    <div></div>
</div> 

CSS

.wrapper {
  position: relative;
}
.wrapper:first-child {
  position: absolute;
  width:50px;
  height:50px;
  top:25px;
  left: 25px; 
  background: red;
  z-index: 100;
}
.wrapper:last-child {
  position: relative;
  width:100px;
  height:100px;
  background: orange;
}

Added

Thanks for all your input. Now I understand where I got this wrong (psuedo class to be applied to child element)

I've made up the sample to isolate my problem but I am actually doing this for <img> elements where one <img> sits on top of the other <img> and the html structure is

<div class="brand">
    <a href="#"><img src=""/></a>
    <a href="#"><img src=""/></a>
</div>

css is

.brand img:last-child {
    position: relative;
}
.brand img:first-child {  
    position: absolute;
    top:10px;
    left:15px;
}

They are not working like the simple div example. I guess that is because there is another anchor element that needs to be taken into account for.

Upvotes: 0

Views: 3739

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You should use .wrapper > div:first-child and .wrapper > div:last-child instead.

.wrapper > div:first-child {
  position: absolute;
  width:50px;
  height:50px;
  top:25px;
  left: 25px; 
  background: red;
  z-index: 100;
}
.wrapper > div:last-child {
  position: relative;
  width:100px;
  height:100px;
  background: orange;
}

As per you edit:

You should do like this

.brand a:last-child img {
    position: relative;
}
.brand a:first-child img {  
    position: absolute;
    top:10px;
    left:15px;
}

Upvotes: 5

Related Questions