• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

My Monkey Do

A Log of Coding Solutions

  • Home
  • Web Hosts
  • Tools
  • About

Pseudo Selector First Child of Class

June 30, 2014 by Webhead

Problem

How do you apply a style to only the first element with a certain class?

.just-this-one {

background:blue;

}

<div class="top">

<div class="not-this-one">not this one</div>
<div class="just-this-one">just this one</div>
<div class="just-this-one">but not really</div>

</div>

:first-child does not do this, that just selects the very first child no matter what the class is.

:first-of-type doesn’t even do this.  but you would think it does, but “type” here implies the HTML element type like “div”, “p”, etc.

 

Solution

Use the tilde “~” to “undo” styles on elements where the class previously appeared.  So first apply the style you want to all .just-this-one elements.  Then apply “undo” that style for all subsequent elements.

.just-this-one {

background:blue;

}

.just-this-one ~ .just-this-one {

background:none;

}

This genius solution found on stack overflow (not the accepted answer):

http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class

 

Additional note:  If you have a pseudo selector like :before, use something like the code below to write content before all li elements except the first one.

.menu li:before {
content: '';
}

.menu li ~ li:before {
content: "\002F\0020\002F";
color: #aaaaaa;
}

 

 

Filed Under: Coding Tagged With: css

Primary Sidebar

Topics

502 apache apple bluehost bootstrap buddypress chrome cloudways cms css debug drupal eCommerce firebug firefox git goDaddy google google analytics google maps hacked hosting htaccess html html 5 icons IE crap image iPad iPhone javascript jquery linux localization mac os x ms sql mysql open source optimize php tinymce wordpress wpengine yii youtube




Categories

  • Coding
  • Off the Shelf
  • Plugins
  • Random Thoughts
  • Server Stuff
  • Tools