Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply CSS to only immediate children of a certain class

Tags:

html

css

I have a div and in that div I want to create another div with a different class and have the inner div completely separated from the outer div CSS settings.

Like this:

<div class="outer">
    <div><h1> h1 </h1><div>
    <div class="inner">
        <h2> h2 </h2>
    </div>
    <h2> h2 </h2>
</div>
.outer h1{ color:blue; }
.outer h2{ color:red; }

.inner { height: 111px; }

What I want is to unset the red color from the h2 in the "inner" div

It might seem stupid not to just overweight the color to black here, but what if I have a lot more arguments in the CSS or even if it's dynamic.

Edit: I guess it isn't clear, but what I need is actually kind of the opposite of the answers I got so far. I have a main-container div and it has alot of settings in the CSS. Now I want to insert a div into the main-container without it having any of the main-container CSS settings.

like image 303
Dvir Levy Avatar asked Feb 27 '12 09:02

Dvir Levy


People also ask

How do I select immediate children only CSS?

The child combinator ( > ) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. Elements matched by the second selector must be the immediate children of the elements matched by the first selector.

How do I apply a CSS to a specific class?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)


2 Answers

.outer > h2 { color:red; } 

this way only the direct child of the outer div get this color value, should fix the job.

like image 50
Tim D'Haene Avatar answered Oct 08 '22 04:10

Tim D'Haene


.outer .inner * { color: #000; } 

sets all elements within the inner container as having the color black.

Demo here

like image 40
Scott Avatar answered Oct 08 '22 05:10

Scott