-1

I just get a bit confused at the concept of div#sidebar, I only knew about #sidebar div,which means to choose the div element when id = sidebar. So what does div#sidebar means? why there is such a method?

Fanali
  • 1
  • Div#sidebar means select only div element with I'd navbar. Whereas #navbar means select any element with id navbar – Gagan Deep May 14 '20 at 08:03

2 Answers2

1

div#sidebar selects a div which has an id of sidebar.

<div id="sidebar"></div>

#sidebar div selects a parent element which has an id of sidebar (which may have any tag name) and uses the descendant selector (a space) to select descendants of the sidebar which are <div>s.

<main id="sidebar>
  <div></div>
  <div></div>
  <article>
    <div></div>
  </article>
</main>

Above, all the <div>s will be targeted.

Snow
  • 3,820
  • 3
  • 13
  • 39
  • Thanks! I guess now I understand it more. The key is whether you want to choose the parent element or not! If you want, you can use div#sidebar,otherwise use #side bar div! – Fanali May 14 '20 at 09:47
0
  • div#sidebar will select <div id="sidebar"> - Select element with specified ID
  • #sidebar div will select <div id="sidebar"><div> - inner div - Select element that has parent with specified ID

div#sidebar,
#sidebar2 div {
  background-color: red;
  opacity: 50%;
}

div {
  border: 2px solid blue;
  padding: 3px;
}
<div id="sidebar"><div>div#sidebar</div></div>
<div id="sidebar2"><div>#sidebar div</div></div>
Justinas
  • 41,402
  • 5
  • 66
  • 96
  • Thanks a lot! I guess the example is quite clear to me. So #sidebar div uses descendants selector, only descentdants element will be chosen. And div#sidebar will choose all the div element named bysidebar and the descentdants will inherit (e.g. the color attribute). Am I right? – Fanali May 14 '20 at 09:44
  • Yes, will apply to descendant `
    ` will have applied this rule (not inherited!). But for example `font-size` will be inherited for all child elements
    – Justinas May 14 '20 at 09:58
  • Oh yes, background-color can't be inheirted. The default bg-color is trasprent. I use this code and test again, now get it! – Fanali May 14 '20 at 10:09
  • `
    #sidebar div
    `
    – Fanali May 14 '20 at 10:09