CSS Practices to avoid as a developer

Mursal Furqan Kumbhar - Dec 12 '21 - - Dev Community

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 😉

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player