Ageis
Ageis

Reputation: 2315

How to select the parent's parent in CSS?

<div id="maincontent">
    <div id="content">
        <div id="admin"></div>
    </div>
</div>

Is it possible to have a rule that would match #maincontent only if #admin exists using just CSS?

It's just I have a background colour in the control panel but don't want it there for visitors.

Upvotes: 0

Views: 3798

Answers (4)

Nissan
Nissan

Reputation: 33

Selecting parent element? well you can with css4!

$#maincontent #admin {
   background:hotpink;
}

Which works.. in .. uhmm.. hh...

However with awesome jquery script, yes sir you can!

cssParentSelector.js

If you love CSS this should come as an absolute tool in many situations

Upvotes: 1

doc_id
doc_id

Reputation: 1443

No not with CSS. Alternatively you may use a CSS class hen viewing for admin. So for an admin

<div id="maincontent" class="adminBackground">
    <div id="content">
        <div id="admin"></div>
    </div>
</div>

And for normal visitors (notice that the class="adminBackground" attribute is removed):

<div id="maincontent">
    <div id="content">
        <div id="admin"></div>
    </div>
</div>

Then define a role for that class "adminBackground":

.adminBackground {
     background: #AAAAAA;
}

Upvotes: 0

Sheavi
Sheavi

Reputation: 250

Unfortunately, you cannot target a node's parent only by using css selectors. You would have to do so by using some Javascript or jQuery. Here are two examples of how to achieve what you want using both javascript and jQuery.

Here's how in javscript:

if (document.getElementById("admin") != null) { // if there is a node with "admin" as ID
    document.getElementById("maincontent").style.backgroundColor = "#000"; // changes the background to black
}

Here's how in jQuery:

if ($("#admin").size() === 1) { // if there is a node with "admin" as ID
    $("#maincontent").css("background-color", "#000"); // changes the background to black
}

Upvotes: 0

nybbler
nybbler

Reputation: 4841

Unfortunately, there is no parent selector in CSS.

You will have to use javascript to do this on the client.

Upvotes: 1

Related Questions