CSS

Improving SCSS PART-1

Cascading Style Sheets

Cascading Style Sheets

Improving SCSS PART-1

We often find examples of stylesheets that can be improved but it is not always easy to have live samples of what goes wrong. Let’s have a peek at some poorly written SCSS code, identify the issues step-by-step and take it to a better place.

Try and spot what seems off about the following:

.gallery-hover-icon {
    &.img-delete-icon-gallery {..}
}
&:hover {
    .gallery-hover-icon {
        display: block;
        .bg-hover {...}
    }
}

Here are all the things that can go wrong when the styles above are compounded with HTML:

<div class="gallery-hover-icon">
    <div class="gallery-checkbox"...>
    <div class="bg-hover">
        <a class="restore-icon-gallery waves-effect waves-light modal-trigger"...>
        <a class="delete-icon-gallery waves-effect waves-light modal-trigger"...>
    </div>
</div>

Firstly, if you see in SCSS .gallery-hover-icon is called twice which is not the practice for writing SCSS, a class should be mentioned only once, instead hierarchy or nesting can be maintained to achieve your desired result.

Secondly, in above HTML snippet, .delete-icon-gallery and .restore-icon-gallery are written inside .bg-hover, if you have a look at its corresponding SCSS you will find that .bg-hover is called inside &:hover which means whenever parent element of .bg-hover is hovered then only .bg-hover class will be called so ultimately .delete-icon-gallery and .restore-icon-gallery will be called only and only when parent is hovered.

Improved SCSS

.gallery-hover-icon {
    .img-delete-icon-gallery {...}
    &:hover {
        display: block;
        .bg-hover {...}
    }
}

Changes Made:

  1. Used .gallery-hover-icon only once.
  2. Shifted the code for hover inside .gallery-hover-icon.
  3. Removed & from &.img-delete-icon-gallery.

Let me know your thoughts