skip to Main Content

In the following code, I don’t understand &:before.

                    .coloring {
                      &:before {
                        background: "black";
                      }
                    }

Is it a built in class or it is a class maybe created by a collaborator?
is & required? (I looked on the web and found that some uses ::before)

2

Answers


  1. The &:before is not a built-in class in CSS. It is a pseudo-element that is used to insert content before the content of an element. The & symbol is a Sass/SCSS syntax that refers to the parent selector. It is used to concatenate the parent selector with the child selector. In the given code, .coloring is the parent selector and &:before is the child selector. The & symbol is used to concatenate the parent selector .coloring with :before pseudo-element. The ::before is the correct syntax for the :before pseudo-element in CSS3 and later versions.

    Login or Signup to reply.
  2. & is the CSS nesting selector. It’s very new and doesn’t have full support in all major browsers yet (although it is getting close).

    The use of a single : is a hang-over from the time before CSS was changed to distinguish pseudo-classes and pseudo-elements with different syntax.

    .coloring {
        &::before {
            background: "black";
        }
    }
    

    is equivalent to:

    .coloring::before {
        background: "black";
    }
    

    It’s not a very practical use here, but consider an example where there were rules applied to both the element itself and the pseudo-element. Then it avoids having to repeat the first part of the selector for two different rule-sets.

    .coloring {
        color: red;
    
        &::before {
            background: "black";
        }
    }
    

    The same syntax is used in SASS.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search