Dragonsnap
Dragonsnap

Reputation: 953

How to Select Multiple Elements inside a div for CSS

This may seem like a really simple question that can be answered by Google, but I have been struggling to figure this out for a while. Say you have an HTML code like this:

    <p> text 1 </p>
    <div class = "divone">
        <p> text 2 </p>
        <h1> text 3 </h1>
    </div>

and if I have CSS setup like this:

    .divone h1, p{
        color: yellow;
    }

It seems to change the p element outside of the div element. What can I do to select the elements inside a div so that it only changes the p inside the div "divone"?

Upvotes: 0

Views: 9324

Answers (4)

Levan Tchumburidze
Levan Tchumburidze

Reputation: 94

p element's parent is not specified, so you should do one of this things:

.divone h1
.divone p {
 color: yellow
 }

or you can use ">" symbol, which effects direct children of element

.divone > h1
.divone > p {
 color: yellow
 }

Upvotes: 1

manoj
manoj

Reputation: 1093

to select immediate children of a specified element. and avoid deeper nesting, use immediate selector ">"

.divone > h1, .divone > p {
    color: yellow;
}

otherwise for selecting all children of parent element use

.divone h1, .divone p {
     color: yellow;
}

Upvotes: -1

Justinas
Justinas

Reputation: 43451

, separates rules, so you must repeat .divone:

.divone h1,
.divone p {
    color: yellow;
}

You can use some CSS preprocessor like LESS or SASS to nest rules:

.divone {
    h1,
    p {
        color: yellow;
    }
}

but it will compile to same CSS rules.


Your current rule .divone h1, p says apply for h1 that is inside .divone or any p element on page

Upvotes: 6

dev
dev

Reputation: 146

.divone h1, .divone p{
     color: yellow;
}

Upvotes: 0

Related Questions