How to combine Sass Ampersand or nesting with attribute selector?

Viewed 40

I would like to different color self element when it is disabled, similar to hover using the sass nested syntax. Is it possible to achive something like the following?

.class {
  color: blue;
  &:hover {
    color: grey;
  }
  &:[disabled] {
    color: red;
  }
}

I know that I can do that without nesting and Sass Ampersand like this:

.class {
  color: blue;
  &:hover {
    color: grey;
  }
}
.class[disabled] {
  color: red;
}

I am curious if this can be achieved with some sort of first solution.

This is how the DOM element looks in the browser.

<div _ngcontent-luo-c245 mat-menu-item disabled="true" class="mat-focus-indicator menu-item mat-menu-item" ng-reflect-disabled role="menuitem" tabindex="-1" aria-disabled="true">...</div>
1 Answers

You don't need to add the square brackets. This is how it should look:

.class {
  color: blue;
  &:hover {
    color: grey;
  }
  &:disabled {
    color: red;
  }
}

So I tested it by creating a html page with button which is disabled on click and changes to color red.

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <button id="test-btn" onclick="this.disabled=true">
        Test Button
    </button>
</body>

</html>

SCSS:

body {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
}

#test-btn {

    width: max-content;
    padding: 1rem;

    &:hover {
        color: #000;
        background-color: #fff;
        border-color: #fff;
    }

    &:disabled {
        color: #fff;
        background-color: #f00;
        border-color: #f00;
    }
}

Here's the preview: Click here

Related