Peter Stuart
Peter Stuart

Reputation: 2434

How do I make CSS styles dependant on its parent element

I was wondering if it is possible to define the styles of an element depending on the value of the body ID.

It is difficult to explain but something like this would be ideal:

HTML:

<body id="home">

CSS:

body#home {
  a { /* code here */ }
  p { /* code here */ }
}

body#profile {
  a { /* different code here */ }
  p { /* different code here */ }
}

I know I can do this:

body#home a { /* code here */ }

but that becomes very repetitive.

I will be looking forward to your responses,

Peter

Upvotes: 4

Views: 2774

Answers (4)

Stuart Kershaw
Stuart Kershaw

Reputation: 17671

Be aware that while nesting styles like this can be supported using CSS frameworks, it should be well thought-out to maintain modularity and clean inheritance in your CSS. You can end up doing more harm than good. In particular, watch out for something know as the inception rule, described here:

http://thesassway.com/beginner/the-inception-rule

The Inception Rule: don’t go more than four levels deep.

Any change you make to your markup will need to be reflected into your Sass and vice versa. It also means that the styles are bounded for life to the those elements and that HTML structure which completely defeats the purpose of the "Cascade" part of "Cascading Style Sheets."

If you follow this path, you might as well go back to writing your CSS inline in your HTML (please don't).

Upvotes: 1

Dan Green-Leipciger
Dan Green-Leipciger

Reputation: 3922

The best way to do what you are talking about is to have a base stylesheet the site.

They have either:

A <style> element in the header overriding anything you choose

or

Have a different stylesheet for each page

Upvotes: 1

brian
brian

Reputation: 812

You can do this if you use a CSS framework like SASS or LESS

Here's the documentation on how to do this with LESS. Hope this helps.

Upvotes: 3

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

IDs are supposed to be unique, so #home { ... } is acceptable.

Then and child elements would be:

#home .myClass { ... }

This technique if often used to re-skin pages be simply changing the ID or class on a body.

Upvotes: 2

Related Questions