David Barker
David Barker

Reputation: 14620

CSS class influencing elements not nested within the class

I have the following HTML in a page feature:

<div id="feature-detail">
    <div class="da1 d-active">
        <h1><span>Detail 1</span></h1>
        <p><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span></p>
        <a href="#"><span>Show how</span></a>       
    </div>
</div>

I then have further down the page:

<div id="page-submain" class="centred">
    <div id="left-widget" class="widget">
        <h1><span>Title</span></h1>
        <p><span>Lorem ipsum dolor sit amet.</span></p>
        <a href="#"><span>Read More</span></a>
    </div>
</div>

NOTE: Neither of the above parent <div> elements are nested within each other. Both have a parent of <body>.

When I run some tests on the CSS structure, I have noticed that this style rule:

.widget p,a,h2 {
    margin:3px 5px 3px 5px;
    padding:0;
}

Is influencing the <a> in #feature-detail. Why is this doing that when I've explicitly applied the style to the class 'widget'?

Not making a huge amount of sense to me at the moment, but it seems that IE, FF, Chrome and Opera are interpretting it exactly the same. Am I missing something here?

Thanks for taking a look!

Upvotes: 0

Views: 99

Answers (4)

Mansoor Gee
Mansoor Gee

Reputation: 1069

The tags and are not nested within .widget class. I have re-formatted the css On jsfiddle . Have a look on it.

Upvotes: 0

Benjie
Benjie

Reputation: 7946

What you've written is equivalent to:

.widget p {
    margin:3px 5px 3px 5px;
    padding:0;
}
a {
    margin:3px 5px 3px 5px;
    padding:0;
}
h2 {
    margin:3px 5px 3px 5px;
    padding:0;
}

What you want is:

.widget p, .widget a, .widget h2 {
    margin:3px 5px 3px 5px;
    padding:0;
}

Upvotes: 3

GolezTrol
GolezTrol

Reputation: 116100

Yes, the comma delimiter means you have actually multiple selectors. So the selector .widget p,a,h2 matches:

  • All P's in .widget
  • All A's, regardless
  • All H2's, regardless.

Change it to:

.widget p, .widget a, .widget h2 {...

Upvotes: 1

James Allardice
James Allardice

Reputation: 165941

The selector used in this:

.widget p,a,h2 {
    margin:3px 5px 3px 5px;
    padding:0;
}

matches "p elements that are a descendant of elements with the class widget", all a elements and all h2 elements.

If you want the a rule to only apply to a elements that are a descendant of an element with the class widget, you need to specify that (and you'd have to do the same with h2 if you want that to behave in a similar way):

.widget p, .widget a, h2

Upvotes: 1

Related Questions