0

I want to apply some css on the basis of dir rtl attribute on body tag

My earlier implementation was below one which was not working

:not([dir="rtl"]) nav > ul > li:last-child a {
    padding-right: 0;
    margin-right: 0;
}

By mentioning body tag its working fine and I am not able to get the reason of same. Any help will be highly appreciated.

body:not([dir="rtl"]) nav > ul > li:last-child a {
    padding-right: 0;
    margin-right: 0;
}
Ranjit Singh
  • 3,715
  • 1
  • 21
  • 35
  • 1
    Probably some other rule is overriding your CSS rule. When you add "body" it increases the specificity of the rule. Try checking the developer console for the applied rules. – K K Feb 10 '20 at 08:25

3 Answers3

2

:not([dir="rtl"]) will effect any element with no [dir="rtl"], means even if the body have it, if any of the elements inside will not have it it still will apply to the child li. Even if the element extend the style, it will apply to it, since its not have the attribute dir with the value rtl.

When you add the body selector, the css will apply only when the body not have this attribute, but if it have, the fact that other elements not have it will not effect.

Yosef Tukachinsky
  • 5,570
  • 1
  • 13
  • 29
1

Assuming you have a DOM structure like

<html>
  <head></head>
  <body dir="rtl">
    <nav>
      <ul>
        <li>
          <a>select me when not rtl</a>
        </li>
      </ul>
    </nav>
  </body>
</html>

then your rule will still see the <html> element as being :not([dir="rtl"]) and thus your rule will still be active, whatever the attribute value on your <body>.

console.log( document.querySelector(':not([dir="rtl"])') ); // <html>
Kaiido
  • 123,334
  • 13
  • 219
  • 285
0

The problem with your earlier version of the CSS is that the first part of the selector :not([dir="rtl"]) could match the <html> element instead of the <body> element, or any other intermediate container between the <body> and the <nav>, which probably has not the dir attribute set.

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177