DEV Community

Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

CSS Practices to avoid as a developer

Set Margins or Padding and then RESET them

We often see developers coding their CSS margin/padding styles and then resetting them manually. Such as:

.item{
     margin-right: 1.6rem;
}

.item:last-child{
     margin-right: 0;
}
Enter fullscreen mode Exit fullscreen mode

Instead of using this extremely unhealthy practice, developers can simply use something like this:

.item:not(:last-child) {
     margin-right: 1.6rem;
}
Enter fullscreen mode Exit fullscreen mode

Set Display:Block for flex items

When using Flexbox, it is important to remember that when you create a flex container (Add Display:Flex), all children (Flex Items) become BLOCKiFIED
Hence, instead of using code like:

.parent {
     display: flex;
}

.child {
     display: block;
}
Enter fullscreen mode Exit fullscreen mode

Developers can simply use

.parent {
     display: flex;
}
Enter fullscreen mode Exit fullscreen mode

Use Width:100% for Block Elements

Since we, the developers already term the element with Display property, we don't need to add an additional width: 100% to it's children. For example, have a look at an example of the practice we need to avoid:

<div class="parent">
     <div class="child">Item 1</div>
     <div class="child">Item 2</div>
     <div class="child">Item 3</div>
     <div class="child">Item 4</div>
     <div class="child">Item 5</div>
</div>
Enter fullscreen mode Exit fullscreen mode
.parent {
     display: flex;
     flex-wrap: wrap;
}

.child {
     width: 100%;
}

@media (min-width: 1024px) {
     .child {
          width: 25%;
     }
}
Enter fullscreen mode Exit fullscreen mode

Instead, developers can switch to the following approach:

<div class="parent">
     <div class="child">Item 1</div>
     <div class="child">Item 2</div>
     <div class="child">Item 3</div>
     <div class="child">Item 4</div>
     <div class="child">Item 5</div>
</div>
Enter fullscreen mode Exit fullscreen mode
@media (min-width: 1024px) {
     .parent {
          display: flex;
          flex-wrap: wrap;
     }

     .child {
          width: 25%;
     }
}
Enter fullscreen mode Exit fullscreen mode

More bad practices in next article 😉

Top comments (2)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

The last one should be:

@media (min-width: 1024px) {
     .parent {
          display: flex;
          flex-flow: row wrap;
     }

     .child {
          flex: 0 1 25%;
          max-width: 25%;
     }
}
Enter fullscreen mode Exit fullscreen mode

To ensure it shows off at the specified size, buggless.

Learn more about here: developer.mozilla.org/en-US/docs/W...

Collapse
 
carolskelly profile image
Carol Skelly

What about avoiding use of !important