Matju
Matju

Reputation: 51

How the styles are used in CSS

Hi I am new to CSS and was playing around. I have this example

HTML:

<div>
    <h4>International News</h4>
    <article>
        <h4 class= "headline"> New Developments! </h4>
        <aside>
            <h4>Impact on Markets</h4>
        </aside>
    </article>
  </div>

CSS:

h4 {color:powderblue;}
.headline{color:red;}
article {color:black;font-style:normal;}
aside h4{font-style:italic !important; color:yellow;}
article h4{font-style:normal; color:sienna;}

Why does the "inside on markets" h4 is using sienna and not yellow color? Sorry if this is a stupid question.

Upvotes: 2

Views: 278

Answers (3)

Rohit
Rohit

Reputation: 324

Try to use following CSS

aside > h4{font-style:italic !important; color:yellow;}
article > h4{font-style:normal; color:sienna;}

here > will force the selector to apply style on direct child/children not to grandchild/grandchildren

Upvotes: -1

Daan
Daan

Reputation: 2799

Because code is correctly read from the top to the bottom.

aside h4{font-style:italic !important; color:yellow;}
article h4{font-style:normal; color:sienna;}

First you give the h4's in aside (and it's children) the color yellow.

This is this one: <h4>Impact on Markets</h4>

Then you give the h4's in article (and it's children) the color sienna.

It instantly overrides the code. If you switch the position of the lines you can see that it now does get yellow.

JSFiddle demo

Upvotes: 1

Quentin
Quentin

Reputation: 943142

See the cascade.

Neither color:yellow nor color:sienna is !important (this is good, !important is horrible).

aside h4 and article h4 both match the element.

aside h4 and article h4 both contain 2 type selectors and nothing else that influences specificity, so are equally specific.

article h4 is defined last, so it is applied last and overrides the previous matching rule.

Upvotes: 5

Related Questions