Responsive CSS Mastery: A Practical Approach to Em and Rem Units Implementation


Nowadays, when you build a website, you also have to keep in mind that the website should be responsive to all the screen sizes that the majority of people use. As more than half of the internet users surf the web on mobile devices, you have to ensure that your website looks good on mobile devices, whether you are building the website for yourself or for clients. To make this process of making the website responsive, you have to understand the CSS units EM and REM.

Understanding Em and Rem

EM (Emphasized): In CSS, “em” is a unit relative to its parent element’s font size. If the parent’s font size is 16 pixels, 1em equals 16 pixels. It’s handy for creating designs that adjust proportionally with text size changes.

.card {
  font-size: 16px; /* Parent font size */
  padding: 1em;    /* Padding is 1 times the parent font size, so it's 16 pixels */

In this example, the card’s padding adapts to the parent font size. If the font size changes to 20 pixels, the padding becomes 20 pixels, maintaining a proportional relationship.

REM (Root Em): Unlike “em,” “rem” is relative to the root element’s font size. If the root font size is 20 pixels, 1rem equals 20 pixels across the entire document. This provides a consistent way to size elements, irrespective of their nesting, simplifying styling across the webpage.

:root {
  font-size: 20px; /* Root font size for the entire document */

.card {
  padding: 1rem;   /* Padding is 1 times the root font size, so it's 20 pixels */

In this case, the card’s padding is based on the root font size. It remains consistent regardless of the parent’s font size, offering predictability and ease of maintenance across different sections of the webpage.

Technical Insight: Both em and rem are relative units, adapting well to diverse screen sizes. Em maintains a relationship with its parent’s font size, while rem is independent, tied only to the root HTML font size.

WHY use EM and REM over Pixels

Now, let’s get into why em and rem are your go-to units. Using these units to set padding and font sizes allows you to orchestrate comprehensive changes with a single action in responsive mode.

Consider this scenario: a media query adjusts the HTML font size to 16 pixels for smaller screens and 25 pixels for larger devices. This simple adjustment orchestrates a smooth transformation throughout the entire website – font sizes, padding, and margins.

Example: If you set your website’s default font size to 16 pixels and use em for padding and font sizes, changing the HTML font size in a media query to 25 pixels for larger screens will automatically adjust everything accordingly.

Leave a Comment

Your email address will not be published. Required fields are marked *