Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

first-child not working

Should this work am I going crazy?

.project.work:first-child:before {
  content: 'Projects';
}
.project.research:first-child:before {
  content: 'Research';
}
<div class="project work">
  <p>abcdef</p>
</div>
<div class="project work">
  <p>abcdef</p>
</div>
<div class="project work">
  <p>abcdef</p>
</div>
<div class="project research">
  <p>abcdef</p>
</div>

projects:first-child works fine, research:first-child doesn't stick. Any ideas?

Demo It doesn't work, but whats the best way to achieve this?

like image 604
uriah Avatar asked Dec 16 '11 14:12

uriah


People also ask

How do I get CSS only for my first child?

The :first-child selector is used to select the specified selector, only if it is the first child of its parent.

How does CSS first child work?

The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

What is the difference between first child and first of type?

The :first-child: The :first-child selector is used to select those elements which are the first-child elements. For :first-child selector the <! DOCTYPE> must be declared for IE8 and earlier versions. The :first-of-type: The :first-of-type Selector is used to targeting the first child of every element of it's parent.

What is first child and last child in CSS?

The :first-child pseudo class means "if this element is the first child of its parent". :last-child means "if this element is the last child of its parent". Note that only element nodes (HTML tags) count, these pseudo-classes ignore text nodes.


1 Answers

:first-child only selects the first child of its parent. Nothing else.

As mentioned in a few of my other answers on the site (1 2 3 4), there is no :first-of-class pseudo-class. If you are looking to apply styles to the first of each class of your div elements, a solution is to apply the styles to all children of that class, and a general sibling selector to undo the styles from subsequent siblings.

Your CSS would then look like this:

.project.work:before {
    content: 'Work';
}

.project.research:before {
    content: 'Research';
}

.project.work ~ .project.work:before, 
.project.research ~ .project.research:before {
    content: none;
}
like image 141
BoltClock Avatar answered Sep 28 '22 10:09

BoltClock