-1

I'm trying to apply :hover only on desktop visitors of a webpage, and :active on the others. I'm setting the mobile class to the body element on the touchscreen devices version, and I put these lines in my css for the buttons in the document (elements with btn class) :

.btn {
    background: blue;
    color: white;
    border-color: white;
}
:not(.mobile) .btn:hover {
    background: red;
    color: blue;
    border-color: black;
}
.mobile .btn:active {
    background: red;
    color: blue;
    border-color: black;
}

Here is an example of how this mobile webpage could be coded :

<html>
  <body class="mobile">
    <h1>TITLE</h1>
    <div class="btn">button</div>
  </body>
</html>

The problem is that when browsing on the mobile page, the :hover pseudo-class is still selected even if the button is a child of the body with the mobile class ! Am I incorrectly understanding :not(.mobile) .btn:hover ?

I think it should select any immediate/distant element that has the btn class and is being hovered, and is a child of an element that doesn't have the mobile class...

I also tried others solutions like media queries, but I couln't get them to work as I expected.

The fiddle : https://jsfiddle.net/162tn8ko/

Thank you for reading my bad english

jhpratt
  • 6,841
  • 16
  • 40
  • 50
ath
  • 11
  • 2
  • why you bother with mobile since there is no hover on mobile? – Temani Afif Oct 19 '18 at 21:52
  • @TemaniAfif I want to keep my code the same for both platforms, with the only difference being the `body` class. The goal of that css is to make hovering effects only happen on desktop platforms – ath Oct 20 '18 at 11:18
  • and this is what I said, by default there is no hover on mobile, you cannot perform the hover action on mobile so no need to bother your self. – Temani Afif Oct 20 '18 at 11:45

2 Answers2

0

Right now, that selector is matching the html element, with the child of div.btn. To ensure it's a direct child, use >.

.btn, .btn_noborder {
 background: blue;
 color: white;
 border-color: white;
}

/* note the following line */
:not(.mobile) > .btn:hover, :not(.mobile) > .btn_noborder:hover {
 background: red;
 color: blue;
 border-color: black;
}
.mobile .btn_noborder:active, .mobile .btn:active {
 background: red;
 color: blue;
 border-color: black;
}
<html>
  <body class="mobile">
    <h1>TITLE</h1>
    <div class="btn_noborder">button</div>
  </body>
</html>
jhpratt
  • 6,841
  • 16
  • 40
  • 50
0

Thank you jhpratt, your answer helped me understand that the :not(s) was indeed applied on the html element. As Temani Afif guessed, in my code the btn is not a direct child of the body ; but here is what I was looking for :

body:not(.mobile) .btn:hover { ... }

complete solution : https://jsfiddle.net/162tn8ko/6/

ath
  • 11
  • 2
  • Please refrain from posting an answer identical to one that I posted. That's what the "accept" checkmark is for. – jhpratt Jul 29 '19 at 21:46