user1469270
user1469270

Reputation:

first-of-type not working as expected

I'm trying to style the first of a series of divs, differently:

http://jsfiddle.net/tmyie/mA3j8/

.slideshow-img-ctnr {
    backround-color: red;
    width: 100px;
    height: 100px;
    border: 1px solid orange;
}
.slideshow-img-ctnr:first-of-type {
    border: 1px solid blue;
}

However, the first div's styling remains the same:

<div class="slideshow-style-ctnr">
    <div class="slideshow-nav">
        <div class="slide-right">&rarr;</div>
        <div class="slide-left">&larr;</div>
    </div>
    <!-- end slideshow-nav -->
    <div class="slideshow-img-ctnr">
        <img src="images/stock/fd-3" alt="">
    </div>
    <!-- end slideshow-img-ctnr -->
    <div class="slideshow-img-ctnr">
        <img src="images/stock/fd-3" alt="">
    </div>
    <!-- end slideshow-img-ctnr -->
    <div class="slideshow-img-ctnr">
        <img src="images/stock/fd-3" alt="">
    </div>
    <!-- end slideshow-img-ctnr -->
    <div class="slideshow-img-ctnr">
        <img src="images/stock/fd-3" alt="">
    </div>
    <!-- end slideshow-img-ctnr -->
    <div class="slideshow-img-ctnr">
        <img src="images/stock/fd-3" alt="">
    </div>
    <!-- end slideshow-img-ctnr -->
    <div class="slideshow-img-ctnr">
        <img src="images/stock/fd-3" alt="">
    </div>
    <!-- end slideshow-img-ctnr -->
</div>

Upvotes: 2

Views: 702

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240878

As pointed out in the comments, :first-of-type is used for element types, not classes.

You should take a look at this excellent explanation by @BoltClock.


In this specific instance, you could using the following:

UPDATED EXAMPLE HERE

.slideshow-style-ctnr :first-child + .slideshow-img-ctnr {
    border: 1px solid blue;
}

However, this method will fail if .slideshow-img-ctnr isn't an adjacent preceding sibling of the first-child of .slideshow-style-ctnr. Here is an example where it wouldn't work.

Though the above may work with the current markup, it would be better just to use the following instead:

WORKING EXAMPLE HERE

.slideshow-img-ctnr {
    backround-color: red;       /* Styling shared by the elements */
    width: 100px;
    height: 100px;
    border:1px solid blue;      /* This will be overwritten */
}

Overwrite the initial border on all preceding sibling elements with class .slideshow-img-ctnr:

.slideshow-img-ctnr ~ .slideshow-img-ctnr {
    border:1px solid orange;
}

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

.slideshow-img-ctnr:first-of-type means: element which has class slideshow-img-ctnr and which is the first of its type within its parent.

Because element with slideshow-img-ctnr class is a div, :first-of-type check if that's the first div in the parent element. It's not, so the element does not match the selector.

Upvotes: 2

Related Questions