Member-only story
12 Coding Examples of Ampersand Usages in Styled Components
Ampersand usages for CSS classes, pseudo classes, pseudo elements, and elements
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:
styled-components
Here is the list of examples:
- CSS Classes
– Example of the.green
selector
– Example of theContainer
component
– Example of the&.green
selector
– Example of the& .green
selector
– Example of the&&&&& .green
selector - Pseudo Classes
– Example of the&:hover
selector
– Example of the& :hover
selector
– Example of the& :is(div):hover
selector - Pseudo Elements
– Example of the&::first-line
…