user2952265
user2952265

Reputation: 1630

How to style nested element that is styled by its parent already

An initial CSS styling cannot be overwritten by a style specificly assigned to it. How shall I structure my CSS or how can I style the nested element with blue type correctly?

js fiddle

HTML

<ul class="listing">
<li>
    <p> There is plenty of wood.</p>
</li>
<li>
    <div class="big">
        <p> This is extra big</p>
    </div>
</li>
</ul>

CSS

.listing li p{
font-size: 1em;
color: red;
}

.big p {
font-size: 2em;
color: blue;
}

Upvotes: 0

Views: 53

Answers (2)

Michelle
Michelle

Reputation: 2712

While the answer you just accepted works, I'd recommend against using CSS selectors like that.

Not only do they slow down the page load when you begin to scale your site, it's bad practice in general. (Read Writing efficient CSS selectors, Code smells in CSS) You should be using the most efficient, straight-forward CSS selectors, and not giving yourself a gigantic headache by targeting descendants after descendants after descendant.

Here is a more minimal solution:

HTML

<ul class="listing">
    <li>
        <p> There is plenty of wood.</p>
    </li>
    <li>
       <p class="big">This is extra big</p>
    </li>
</ul>

CSS

.listing p {
    font-size: 1em;
    color: red;
}

.listing .big {
    font-size: 2em;
    color: blue;
}

http://jsfiddle.net/BKLrS/4/

Although I'd very much recommend taking this further and doing this: http://jsfiddle.net/BKLrS/5/

Upvotes: 1

The Alpha
The Alpha

Reputation: 146191

You may try this (Example)

div.big p {
    font-size: 2em;
    color: blue;
}

it's all about specificity, check this article as well.

Update : Also you can be more specific like this

.listing li div.big p {
    font-size: 2em;
    color: blue;
}

Upvotes: 2

Related Questions