Top 10 tips For Writing Modern CSS

Aadhavanm
Aadhavanm
Apr 1 · 6 min read

In this post, we want to share with you a collection of 20 useful conventions and best practices that are recommended by the CSS community. Some are tailored more towards beginners, and some are a bit advanced, but we hope everyone will find a cool trick they didn’t know about. Enjoy!

1. Beware of Margin Collapse

Unlike most other properties, vertical margins collapse when they meet. What this means is that when the bottom margin of one element touches the top margin of another, only the bigger of the two survive. Here is a simple example:

.square {
width: 80px;
height: 80px;
}
.red {
background-color: #F44336;
margin-bottom: 40px;
}
.blue {
background-color: #2196F3;
margin-top: 30px;
}

Instead of 70px between the red and blue square, we have only 40px, the margin of the blue square isn’t taken into consideration at all. There are ways to battle this behavior, but it’s better to just work with it and use margins only going in one direction, preferably margin-bottom.

2. Images as Background

When adding images to your design, especially if it’s going to be responsive, use a <div> tag with the background CSS property instead of <img> elements.

This may seem like more work for nothing, but it actually makes it much easier to style images properly, keeping their original size and aspect ratio, thanks to background-size, background-position, and other properties.

img {
width: 300px;
height: 200px;
}
div {
width: 300px;
height: 200px;
background: url(‘https://tutorialzine.com/media/2016/08/bicycle.jpg');
background-position: center center;
background-size: cover;
}
section{
float: left;
margin: 15px;
}

A drawback of this technique is that the web accessibility of your page will take a slight hit, as images won’t be crawled properly by screen readers and search engines. This issue can be resolved by the awesome object-fit but it doesn’t have full browser support yet.

3. Do a CSS Reset

Although the situation has greatly improved over the years, there is still plenty of variation in the way different browsers behave. The best way to resolve this issue is to apply a CSS reset that sets universal default values for all elements, allowing you to start working on a clean style sheet that will yield the same result everywhere.

There are libraries like normalize.css, mini reset, and ress that do this very well, correcting all imaginable browser inconsistencies. If you don’t want to use a library, you can do a very basic CSS reset yourself with these styles:

* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

This may seem a bit harsh, but nullifying margins and paddings actually makes laying out elements much easier as there are no default spaces between them to take into account. The box-sizing: border-box; property is another good default, which we will talk about more in our next tip.

4. Border-box for All

Most beginners don’t know about the box-sizing property but it's actually quite important. The best way to understand what it does is to look at its two possible values:

  • content-box (default) - When we set a width/height to an element, that's just the size for its content. All paddings and borders are on top of that. E.g. a <div> has a width of 100 and padding of 10, our element will take up 120 pixels (100 + 2*10).
  • border-box - The padding and border are included in the width/height. A <div> with width: 100px; and box-sizing: border-box; will be 100 pixels wide no matter what paddings or borders are added.

Setting border-box to all elements makes it so much easier to style everything since you don’t have to do math all the time.

5. CSS Animations with transform

Don’t animate elements by directly changing their width and height, or left/top/bottom/right. It's preferred to use the transform() property as it provides smoother transitions and makes your intentions easier to understand when reading the code.

Here’s an example. We want to animate a ball and slide it out to the right. Instead of changing the value of left, it's better to use translateX():

.ball {
left: 50px;
transition: 0.4s ease-out;
}
/* Not Cool*/
.ball.slide-out {
left: 500px;
}
/* Cool*/
.ball.slide-out {
transform: translateX(450px);
}

Transform, as well as all of its many functions (translate, rotate, scale, etc.) have almost universal browser compatibility and can be used freely.

6. Caps Lock For Meaning, text-transform For Style

In the HTML, write upper case letters when you want to use them for their intended semantic meaning, like when you want to emphasize the importance of a word.

<h3>Employees MUST wear a helmet!</h3>

If you need to have some text in all caps for stylistic reasons, write the text normally in the HTML, and transform it to all-caps with CSS. It will look the same but your content will make more sense if taken out of context.

<div class="movie-poster">Star Wars: The Force Awakens</div>.movie-poster {
text-transform: uppercase;
}

The same goes for lowercasing and capitalizing strings — text-transform handles those just as well.

7. Don’t Use !important

Seriously, don’t. What is a quick fix now that may end up causing lots of rewrites in the future? Instead, find why your CSS selector isn’t working and change it.

The only time when it’s acceptable to !important CSS rules are when you want to override inline styles from the HTML, which in itself is another bad practice to be avoided.

8. Creating Equal Height Columns

This may not seem like a difficult task at first, but making columns that have the same height can be really annoying. Simply setting min-height won't work, because once the amount of content in the columns starts to differ, some of them will grow and others will remain shorter.

Fixing this issue using flexbox couldn’t be easier, as columns created this way have equal heights by default. All we have to do is initialize the flex model, then make sure the flex-direction and align-items properties have their default values.

HTML :<div class="container">

<!-- Equal height columns -->

<div>...</div>
<div>...</div>
<div>...</div>

</div>
CSS :.container {
/* Initialize the flex model */
display: flex;
/* These are the default values but you can set them anyway */
flex-direction: row;
/* Items inside the container will be positioned horizontally */
align-items: stretch;
/* Items inside the container will take up it's entire height */
}

9. Calculating Values With calc()

Another new and awesome CSS feature is the calc() function. It allows you to do simple arithmetic calculations in CSS. You can use it anywhere a length or a size is required. What is even cooler, is that you can freely mix different units, like percentages and pixels. This makes a lot of layout hacks that you might have used in the past obsolete. The best news? It works in IE9 and up, prefix-free.

.container{/* Calculate the width */
width: calc(100% — 40px);
background-color:#CDEBC4;
color:#6D8B64;
text-align:center;
padding:25px 0;
margin: 0 auto;
}

10. Validate

Validating CSS might not be as important as validating HTML or JavaScript code, but running your code through a CSS Linter can still be very helpful. It will tell you if you’ve made any mistakes, warn you about bad practices, and give you general tips for improving the code.

Just like minfiers and autoprefixers, there are plenty of free validators available:

That’s it! We’re done with 10 tips for writing modern CSS.

If you like this article, do like and share :)

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store