Vivian River
Vivian River

Reputation: 32400

How to select a child element in CSS?

I have some HTML that looks like this:

<h2>Heading</h2>
<div class='myClass'>
    <h2>Another Heading</h2>
</div>

Suppose that I want all h2 elements that are contained within a div with class myClass to be underlined.

What is the appropriate CSS selector for this? Note that this is for a static CSS file, not jQuery.

I've tried the following code, but it doesn't work. Bonus points if you can tell me what this incorrect selector selects.

div.myClass > h2 { text-decoration: underline; }

Upvotes: 0

Views: 759

Answers (2)

Jason Gennaro
Jason Gennaro

Reputation: 34863

That should work unless you have a problem with specificity (which it doesn't look like, from the code) or you are using a very old browser.

In your case, this should do the same:

div.myClass h2 { text-decoration: underline; }

You might want to see if it works.

Also, if possible... share a http://jsfiddle.net or link to your code.

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 360016

If I had to guess, I'd say it looks like a CSS specificity problem. That selector alone is correct.

Use a tool such as Firebug to inspect the <h2> element, and see what other CSS rules are applied.

Upvotes: 1

Related Questions