Alexei Vinogradov
Alexei Vinogradov

Reputation: 1608

CSS selector for the first element of class

How can I choose only the first button in this code?

It's even more nested in my case, but this code is also a problem for me.

<div class="container">
  <div class="some_class">
    <span>abc</span>
    <button class="btn">...</button>
  </div>
  <div class="some_class">
    <span>abc</span>
    <button class="btn">...</button>
  </div>
  <div class="some_class">
    <span>abc</span>
    <button class="btn">...</button>
  </div>
</div>

Upvotes: 4

Views: 19700

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240928

You would use the :first-child pseudo class.

EXAMPLE HERE

.container .some_class:first-child button {
    background:black;
}

Alternatively, assuming that the markup can be different, you might need to use something like this to ensure that the first button is selected even if .some_class isn't the first element. (example)

.container :first-child button {
    background:black;
}

Upvotes: 3

Huangism
Huangism

Reputation: 16438

This will work

.container .some_class:first-child button {
    /* rules here */
}

http://jsfiddle.net/cUu82/1/

you could just use .some_class:first-child button as well if these are the only ones on the page

The first-child (https://developer.mozilla.org/en/docs/Web/CSS/:first-child) will select the first some_class div which was probably your only issue

Upvotes: 2

Related Questions