Computer Magic Logo
Nesting

Sunday, June 7, 2015

Published by Aristotelis Pitaridis

Often in CSS we have the phenomenon to have multiple selectors to apply formatting to nested elements. In this case very easily in simple CSS can become confused and have multiple formatting statements for the same item. Other times you can put the wrong path for selecting the element and this will have as a result not to apply the formatting to the item you want or even worse the formatting applied to the wrong element.

In Less we can have nested declarations and this will have as a result to eliminate the possibility of error and makes it easier to edit the code later. Below we can see an example of nested declarations in Less:

#header {
    background-color: lightgray;
    h1 {
        font-size: 32px;
    }
    p {
        font-size: 14px;
        color: darkgray;
        a {
            text-decoration: none;
            &:hover {
                color: darkblue;
            }
            &:visited {
                text-decoration: underline;
            }
            &:active {
                color: darkblue;
                text-decoration: underline;
            }
        }
    }
}

As we see our code became more structured. The future understanding and processing the code becomes easier. The character & is used in front of the pseudo classes to tell the compiler that what follows after the & character is not an element but a pseudo class. The generated CSS code is the following:

#header {
    background-color: lightgray;
}
#header h1 {
    font-size: 32px;
}
#header p {
    font-size: 14px;
    color: darkgray;
}
#header p a {
    text-decoration: none;
}
#header p a:hover {
    color: darkblue;
}
#header p a:visited {
    text-decoration: underline;
}
#header p a:active {
    color: darkblue;
    text-decoration: underline;
}