SECRET OF CSS

12 Coding Examples of Ampersand Usages in Styled Components | by Jennifer Fu | Jul, 2022


Ampersand usages for CSS classes, pseudo classes, pseudo elements, and elements

0*K4zpwYL0nV4G y 1
Photo by TJ Arnold on Unsplash

styled-components is a popular library to style React applications. We have introduced what it is and how to use it and provided 7 ways to inherit styles using styled components.

In this article, we are going to talk about ampersand usages. In styled-components, & (ampersand) is used to refer to all instances of the component. Supported by the preprocessor, stylis, & is used to write clean code for nesting. & originates from Sass and Less, which are CSS extensions.

We reused the Create React App working environment in the last article to explore the ampersand usages. The following package has been installed in the environment:

Here is the list of examples:

In HTML, the class attribute is used to specify class(es) for an element. It can be set to any type of element, and it can take multiple class names that are separated by a space. A class can be used by multiple elements, and the class name is case sensitive.

Example of the .green selector

In CSS, class names are commonly used to style elements.

We create an element that has className set to container. The following is src/App.js:

At line 1, ./App.css is imported.

At line 4, the div element sets className to container.

Here is the CSS rule defined by the container class selector in src/App.css:

Execute npm start, and we see the following UI with the blue background:

Text with the blue background
Image by author

Here is the inspect window:

It shows that div is applied with the .container CSS rule defined in App.css.
Image by author

It shows that div is applied with the .container CSS rule defined in App.css.

Example of the Container component

Class-related selectors can be replaced by styled-components — custom React components. It is easy to track which components are unused or undefined during compilation. It improves code manageability, comparing class names or other ways. Since it is CSS in JavaScript, it enables dynamic styling with programming capability.

We create a styled component, Container. The following is an example of the Container component in src/App.js:

At line 1, styled, instead of ./App.css, is imported.

At lines 3–8, the styled component, Container, extends the styles of div. It contains CSS properties defined in src/App.css.

Execute npm start, and it works.

Text with the blue background
Image by author

Here is the inspect window:

In the example, the static class is sc-gsnTZi, and the dynamic class is gDYWIg, which defines styles.
Image by author

Internally, styled-components generates two classes for each component— one is static and one is dynamic. The class name is generated by MurmurHash algorithm. It generates a unique identifier based on the component id and the evaluated style strings, and then, the hash number is converted to the alphabetic class name.

The static class name is sc-<hashedStringName>. It is used to identify the styled component, and there are no styles attached to it. The name will be the same for all instances. In the example, the static class is sc-gsnTZi.

The dynamic class name may be different for each instance, based on what the interpolations result in. In the example, the dynamic class is gDYWIg, which defines styles.

Example of the &.green selector

For all the benefits of styled-components, it is recommended to use styled-components to style. However, we may not be able to avoid using classes. For example, if we use a third-party library, such as the Ant Design System, there will be classes defined by the library.

& is effective to handle multiple/nesting classes. The CSS selector, .class1.class2, selects all elements with class set to both class1 and class2. Equivalently, &.class selects the styled component itself with class set to class.

Here is an example of &.green in src/App.js:

At lines 8–10, the selector, &.green, sets the CSS property to the green background. This selector is matched by the element at line 14.

Execute npm start, and we see the green background.

Text with the green background
Image by author

Here is the inspect window:

Internally, styled-components generates the classes, sc-eCYdqJ and gdGwCe, for Container. .gdGwCe.green and .gdGwCe are generated CSS rules.
Image by author

Internally, styled-components generates the classes, sc-eCYdqJ and gdGwCe, for Container. .gdGwCe.green and .gdGwCe are generated CSS rules.

Example of the & .green selector

The CSS selector, .class1 .class2 (with a space in the middle), selects all class2 elements that is a descendant of a class1 element. Equivalently, &. class selects all class elements within the specific styled component.

Here is an example of &. green in src/App.js:

At lines 8–10, the selector, &. green, sets the CSS property to the green background. This selector will be matched by the element at line 19.

Execute npm start, and we see the green background for P2.

Text with the blue background, but P2 with the green background
Image by author

Here is the inspect window:

Internally, styled-components generates the classes, sc-hKMtZM and jekZWP, for Container. .jekZWP .green and .jekZWP are generated CSS rules.
Image by author

Internally, styled-components generates the classes, sc-hKMtZM and jekZWP, for Container. .jekZWP .green and .jekZWP are generated CSS rules.

Example of the &&&&& .green selector

Specificity is the algorithm used by browsers to determine the CSS rule that is the most relevant to the element, which in turn determines the property value to apply to the element. The !important rule can be used to add more importance to a property/value than normal, but that is error prone and generally not a good idea.

A better way to override styles with high specificity is to increase the specified styles. Since each & is replaced with the generated dynamic class, the high specificity can be achieved by repeating &.

Here is an example of &&&&& .green in src/App.js:

At lines 8–10, the selector, &&&&&. green sets the CSS property to the green background. This selector will be matched by the element at line 19.

Execute npm start, and we see the green background for P2. The UI looks the same as the selector, &. green.

Text with the blue background, but P2 with the green background
Image by author

However, the inspect window shows the difference:

Internally, styled-components generates the classes, sc-gsnTZi and hFatIX, for Container. .hFatIX.hFatIX.hFatIX.hFatIX.hFatIX .green and .hFatIX are generated CSS rules.
Image by author

Internally, styled-components generates the classes, sc-gsnTZi and hFatIX, for Container. .hFatIX.hFatIX.hFatIX.hFatIX.hFatIX .green and .hFatIX are generated CSS rules.

Is that enough specificity?

A pseudo class is a keyword added to a selector that specifies a special state of the selected element(s). For example, :hover is commonly used to select the element when the user’s pointer hovers over it. The following is the list of pseudo classes: :active, :any-link, :autofill, :blank (experimental), :checked, :current(experimental), :default, :defined, :dir() (experimental), :disabled, :empty, :enabled, :first, :first-child, :first-of-type, :fullscreen, :future (experimental), :focus, :focus-visible, :focus-within, :has() (experimental), :host, :host(), :host-context (experimental), :hover, :indeterminate, :in-range, :invalid, :is(), :lang(), :last-child, :last-of-type, :left, :link, :local-link (experimental), :not(), :nth-child(), :nth-col() (experimental), :nth-last-child(), :nth-last-col() (experimental), :nth-last-of-type(), :nth-of-type(), :only-child, :only-of-type, :optional, :out-of-range, :past (experimental), :picture-in-picture, :placeholder-shown, :paused, :playing, :read-only, :read-write, :required, :right, :root, :scope, :state() (experimental), :target, :target-within (experimental), :user-invalid (experimental), :valid, :visited, and :where().

Example of the &:hover selector

& can be used for psuedo classes. &:hover selects the styled component itself with the state on :hover.

Here is an example of &:hover in src/App.js:

At lines 8–10, the selector, &:hover, sets the CSS property to the green background. This selector will be matched when the pointer hovers over any content in Container.

Execute npm start, and we see the green background when the pointer hovers over Container.

Text with the green background
Image by author

Here is the inspect window:

Internally, styled-components generates the classes, sc-eCYdqJ and zjyfz, for Container. When the hover state is selected, .zjyfz:hover and .zjyfz are generated CSS rules.
Image by author

Internally, styled-components generates the classes, sc-eCYdqJ and zjyfz, for Container. When the hover state is selected, .zjyfz:hover and .zjyfz are generated CSS rules.

Example of the & :hover selector

&: hover selects the styled component descendent with the state on :hover.

Here is an example of & :hover in src/App.js:

At lines 8–10, the selector, & :hover, sets the CSS property to the green background. This selector will be matched when the pointer hovers over Container’s descendant content.

Execute npm start, and we see the green background when the pointer hovers over P2.

Text with the blue background, but P2 with the green background
Image by author

Here is the inspect window:

Internally, styled-components generates the classes, sc-bczRLJ and iLhEec, for Container. When the hover state is selected, .iLhEec :hover and .iLhEec are generated CSS rules.
Image by author

Internally, styled-components generates the classes, sc-bczRLJ and iLhEec, for Container. When the hover state is selected, .iLhEec :hover and .iLhEec are generated CSS rules.

Example of the & :is(div):hover selector

Multiple pseudo classes can be used anywhere in selectors. & :is(div):hover selects the styled component descendent that is a div with the state on :hover.

Here is an example of & :is(div):hover in src/App.js:

At lines 8–10, the selector, & :is(div):hover, sets the CSS property to the green background. This selector will be matched when the pointer hovers over Container’s descendant div.

Execute npm start, and we see the green background when the pointer hovers over P1.

Text with the blue background, but P1 with the green background
Image by author

Here is the inspect window:

Internally, styled-components generates the classes, sc-bczRLJ and iQEDuO, for Container. When div’s hover state is selected, .iQEDuO is(div):hover and .iQEDuO are generated CSS rules.

Internally, styled-components generates the classes, sc-bczRLJ and iQEDuO, for Container. When div’s hover state is selected, .iQEDuO is(div):hover and .iQEDuO are generated CSS rules.

A CSS pseudo element is a keyword added to a selector that can be used to style a specific part of the selected element(s). For example, ::first-line can be used to change the background of the first line of a paragraph. A pseudo element is appended after the last simple selector of the selector.

As a rule, double colons (::) should be used instead of a single colon (:). This distinguishes pseudo classes from pseudo elements. However, since this distinction was not present in older versions of the W3C spec, most browsers support both syntaxes for the original pseudo elements.

The following is the list of pseudo elements: ::after (:after), ::backdrop, ::before (:before), ::cue, ::cue-region, ::first-letter (:first-letter), ::first-line (:first-line), ::file-selector-button, ::grammar-error (experimental), ::marker, ::part(), ::placeholder, ::selection, ::slotted(), ::spelling-error (experimental), and ::target-text (experimental).

Pseudo classes can target an element when it is in a particular state, as if we had added a CSS class for that state to the DOM. Pseudo elements act as if we had added a whole new element to the DOM, which can be styled.

Example of the &::first-line selector

The ::first-line pseudo element applies styles to the first line of a block-level element.

Here is an example of &::first-line in src/App.js:

At lines 8–10, the selector, &::first-line, sets the CSS property to the green background. This selector applies to the first line of Container.

Execute npm start, and we see the green background of the first line.

Text with the blue background, but first line of P1 with the green background
Image by author

Here is the inspect window:

Internally, styled-components generates the classes, sc-gsnTZi and jmHpQT, for Container. .jmHpQT::first-line and .jmHpQT are generated CSS rules.
Image by author

Internally, styled-components generates the classes, sc-gsnTZi and jmHpQT, for Container. .jmHpQT::first-line and .jmHpQT are generated CSS rules.

Example of both & ::before and & ::first-line selectors

The ::before pseudo element creates the first child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.

Here is an example of both & ::before and &::first-line in src/App.js:

At lines 8–10, the selector, & ::before, creates Container descendant’s first child to be viewed as * . This selector applies to div elements at lines 18–23 and 24–28.

At lines 11–13, the selector, & ::first-line, sets the CSS property to the green background. This selector applies to the first line text of Container’s descendants — div elements at lines 18–23 and 24–28.

Execute npm start, and we see the before content and the green background of the first line.

Text with the blue background, but first line of P1 and P2 with the green background
Image by author

Here is the inspect window:

Internally, styled-components generates the classes, sc-bczRLJ and bvMpeg, for Container. .bvMpeg, .bvMpeg ::before, and .bvMpeg ::first-line are generated CSS rules.
Image by author

Internally, styled-components generates the classes, sc-bczRLJ and bvMpeg, for Container. .bvMpeg, .bvMpeg ::before, and .bvMpeg ::first-line are generated CSS rules.

& is used to refer to all instances of a styled component. It acts similar to elements in CSS selectors. All CSS rules for elements are applicable to &.

Example of the & div selector

The CSS selector, element1 element2, selects all element2 inside element1. Equivalently, & div selects the style component’s all descendant div.

Here is an example of & div in src/App.js:

At lines 8–10, the selector, & div, sets the CSS property to the green background. This selector will be matched by the element at line 19.

Execute npm start, and we see the green background for P2.

Text with the blue background, but P2 with the green background
Image by author

Here is the inspect window:

Internally, styled-components generates the classes, sc-bczRLJ and fdLUHb, for Container. .fdLUHb div and .fdLUHb are generated CSS rules.
Image by author

Internally, styled-components generates the classes, sc-bczRLJ and fdLUHb, for Container. .fdLUHb div and .fdLUHb are generated CSS rules.

Example of the span & selector

span &selects the style components that are the descendants of span.

Here is an example of span & in src/App.js:

At lines 8–10, the selector, span &, sets the CSS property to the green background. This selector will be matched by the element at lines 27–29.

Execute npm start, and we see the green background for the first paragraph.

First paragraph with the green background, and second paragraph with the blue background
Image by author

Here is the inspect window:

Internally, styled-components generates the classes, sc-bczRLJ and cqdwhw, for Container. span .sc-bczRLJ and .cqdwhw are generated CSS rules.
Image by author

Internally, styled-components generates the classes, sc-bczRLJ and cqdwhw, for Container. span .sc-bczRLJ and .cqdwhw are generated CSS rules.

Example of the & + & selector

The CSS selector, element1 + element2, selects the first element2 placed immediately after element1. Equivalently, & + & selects the styled component that is placed immediately after the same styled component.

Here is an example of & + & in src/App.js:

At lines 8–10, the selector, & + &, sets the CSS property to the green background. This selector will be matched by the Paragraph element at line 28.

Execute npm start, and we see the green background for the second paragraph.

First paragraph with the bue background, and second paragraph with the green background
Image by author

Here is the inspect window:

Internally, styled-components generates the classes, sc-bczRLJ and himWHV, for Container. .sc-bczRLJ .sc-bczRLJ and .himWHV are generated CSS rules.
Image by author

Internally, styled-components generates the classes, sc-bczRLJ and himWHV, for Container. .sc-bczRLJ .sc-bczRLJ and .himWHV are generated CSS rules.

styled-components is a popular library to style React applications. It is widely adopted by React projects. We have shown 12 coding examples of ampersand usages. Hopefully, it makes your code clean and effective.

Thanks for reading.



News Credit

%d bloggers like this: