Chose Language:
Author: Admin/Publisher |finished | checked

Native CSS Nesting

Since 2023, we can use nested CSS natively, which allows for much clearer and more understandable stylesheets. But let’s go back in time to understand the difference that having this at our disposal makes.

Let’s suppose we have some CSS code from the past, for example, for a button:

style for a red button
button.redbutton{
  background-color :red;
  padding:5px;
  color:white;
  text-transform: uppercase;
  font-size:9px;
}

button.redbutton:hover{
  background-color:lightcoral;
  color: black;
}

The corresponding HTML for the button:

<button class="redbutton">
  mi boton
</button>

The previous code is quite simple: when we hover over the button, its characteristics change. However, having code like this in a large stylesheet can be cumbersome.

It’s better to have code blocks for elements. For example, this code is for my red button, so I group everything related to my red button. Similarly, we could do this for forms, whose styles are usually much more extensive, etc.

Nowadays, we have what is called nested CSS or CSS nesting.

Let’s go back to our CSS for the red button, but this time using nested CSS:

button.redbutton{
  background-color :red;
  padding:5px;
  color:white;
  text-transform: uppercase;
  font-size:9px;

  &:hover{
    background-color:lightcoral;
    color: black;
  }
}

This code is much easier to follow. Notice that we have the button.redbutton block, and within this block, we have the &:hover block. This & refers to button.redbutton.

We can use this way of writing CSS in conjunction with >, +, and other types of selectors to create more complex stylesheets.

Below is a more complex example that I asked ChatGPT for, so it might not be perfect, but it gives you an idea of what nested CSS solves:

form {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 5px;

  .form-group {
    margin-bottom: 15px;

    label {
      display: block;
      margin-bottom: 5px;
    }

    input[type="text"],
    input[type="email"] {
      width: 100%;
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }

    &.error {
      input {
        border-color: red;
      }

      .error-message {
        color: red;
        font-size: 12px;
      }
    }
  }

  button.submit {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;

    &:hover {
      background-color: #45a049;
    }
  }
}
Category: en-others
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category