Nested CSS
Overview
Modern nested CSS is a way to write CSS that is more readable and maintainable, especially for large projects. It allows you to nest CSS rules inside other rules, which can help to keep your styles organized and potentially reduce the amount of CSS data that needs to be downloaded.
File structure is also important when using nested CSS. It is common to have a main CSS file that imports other CSS files, which can be organized by components or features. This allows you to keep your styles modular and easier to manage.
In this activity, you will learn how to use nested CSS.
Prepare
Here is an example of nested CSS:
.container {
display: flex;
flex-direction: column;
place-items: center;
h1 {
font-size: 2rem;
color: #333;
}
p {
font-size: 1rem;
color: #666;
}
button {
background-color: #007BFF;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
&:hover {
background-color: #0056b3;
}
&:focus {
outline: none;
box-shadow: 0 0 0 2px rgb(0 123 255 / 50%);
}
}
}
In the example above, the .container
class contains nested rules for h1
,
p
,
and button
elements. The button also has nested rules for the :hover
and
:focus
states.
Activity Instructions
Convert this traditional CSS into a modern, nested CSS format.
footer {
background-color: #333;
color: white;
padding: 20px;
position: relative;
bottom: 0;
width: 100%;
z-index: 1000;
}
footer a {
color: white;
text-decoration: none;
}
footer a:hover {
text-decoration: underline;
color: yellow;
}
footer p {
font-size: smaller;
}
Check Your Understanding
footer {
background-color: #333;
color: white;
padding: 20px;
position: relative;
bottom: 0;
width: 100%;
z-index: 1000;
& a {
color: white;
text-decoration: none;
&:hover {
text-decoration: underline;
color: yellow;
}
}
& p {
font-size: smaller;
}
}
In this example, child selectors like a {} or p {} are automatically treated as nested selectors relative to the parent and so the & that precedes them may be omitted.
Media queries can be nested directly inside a style rule to apply styles to that parent selector under specific conditions. For example, if you wanted to apply a different style to the footer when the screen width is less than 600px, you could do it like this:
footer {
background-color: #333;
color: white;
padding: 20px;
position: relative;
bottom: 0;
width: 100%;
z-index: 1000;
@media (max-width: 600px) {
background-color: #444;
padding: 10px;
font-size: smaller;
}
& a {
color: white;
text-decoration: none;
&:hover {
text-decoration: underline;
color: yellow;
}
}
& p {
font-size: smaller;
}
}
Optional Resources
- CSS nesting – MDN