Question

I have a piece of HTML code like this one:

<div id="a">
  <p>A piece of HTML</p>
<div>

According to some conditions it will be placed differently into a page and consequently I need to give it different styles.

It could be placed either like this

Case 1

<div id="container">
  <div id="b">
    <div id="a"></div> 
  </div>     
<div>

or

Case 2

<div id="container">
  <div id="b"></div>
  <div id="a"></div>
<div>

I'm wondering what would be the better way (if any exists and taking into account both best practices and performances) to recognize this 2 different cases and style the #a div differently using CSS rules.

Should I assign two different classes for each case and then detect add some CSS rules like this:

#a.class-for-case-1{
  /* Rules here */
}

#a.class-for-case-2{
  /* Rules here */
}

or use a specificity selector like the + selector:

#b #a{
  /* Rules here */
}

#b + #a{
  /* Rules here */
}

or even use a default style for #a div that should be overwritten from the + selector?

#a{
  /* Default rules here */
}

#b + #a{
  /* Specific rules here */
}

Thank you in advance and forgive me if there are similar questions that I didn't notice.

Was it helpful?

Solution

Fastest Option (I think)

I haven't tested, it is just based off how I understand things to work. Assuming those are the only two cases, you should do this:

#a {
  /* Default rules here */
}

#b #a {
  /* Override rules here */
}

The lone default #a id selector is about the fastest selector there is, since the element should be unique on the page and there is only one check needed to apply the rules. So set a default style with that.

The override rule will be nearly as fast, as the browser will encounter the unique id of #b doing one more check up the DOM tree from #a, and apply those rules instead (if it is a child of #b obviously). Of course, we are talking minor differences in efficiency here.

Do realize that any styles applied to #a through those selectors will have a fairly high specificity (especially the nested version), and therefore not able to be overridden by any mere .someClass css you or javacript may try to apply. But that may be totally fine, depending on your context. It is this high specificity that makes changing css on those elements later that cause some to steer away from using id's at all for applying css properties, but I feel that it all depends on the context of the site whether it is a good or bad thing to use id's for that.

OTHER TIPS

As you have the two case: you can do the following:

#b #a{/*css code here for first case*/}
#container > #a{/*css code here for second case*/}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top