How to access CSS children properly?

Tags: html,css

Problem :

If I want to change the background of the first 2 <div> in this HTML code inside the "main" <div>


<div class="main">

Is this the most optimal way to do this?


.main div:nth-of-type(1),
.main div:nth-of-type(2) {
    background: #000;

Solution :

You can set ranges with nth-child. To start from a position (defined by the last part + 2) and select all children that follow, use n, if you want to select all elements before the position, use -n. (Inclusive in both cases.)

More tips and tricks concerning nth-child here.

.main div:nth-of-type(-n+2) {
    background: #000;
<div class="main">

    CSS Howto..

    How to remove the effect of all the parent containers on any child control

    How to show borders of th elements with gradient fills in IE9?

    how to conditionally transform div to and from a state on multiple presses of same button

    How to avoid calling “” for my CSS files

    How to properly float this image verticaly aligned?

    how to make css nested colors in one div bacground

    How to position divs inline with same spacing

    How to prevent css borders from floating to the top of parent div

    How to use css to display an avatar pic with details next to it?

    How to generate the following control using html and css

    Javascript Slider not showing and Graph tips

    How to partly color the border with css [closed]

    How should I set a custom style on a object that is a gwt component?

    In css how to joining two div classes without space? [closed]

    How to use min-width for “float:right” element in CSS?

    CSS: How to fix overlapping divs

    How to reset input element style

    Trying to incorperate a really simple light box. How do I stay centered on scroll?

    how to style margins between items in a

    how to add a different css to last mysql query result using php

    How to fix Image on top of text with css

    How to fix internet explorer 9 overflow with form elements displayed in a list and “display:table”-based layout

    How do I prevent my dropdown from closing when clicking inside it?

    How to work with fixed positioning in CSS?

    How to solve outlook client css layout change properties?

    Div is laying ontop of absolute-positioned element. How to put element above the div?

    html - how to make images stay on certain part of background

    How to format an HTML table using CSS for printing?

    How to fill in blank space using html and css

    how to add items into a CSS based text rotator (similar to news ticker)