thumbnail

How to Use Rem Units in CSS?

How to Use Rem Units in CSS?

Rem units are a powerful tool for creating scalable and maintainable CSS. They allow you to size elements relative to the root font size, which makes it easy to adjust the overall size of your website without having to change a bunch of individual element sizes.

Font Sizing

Use rem for font sizes to scale with user settings.

h1 {
      font-size: 2rem; /* 32px if root font-size is 16px */
    }

Media Queries

Use rem in media queries for responsive design.

@media (min-width: 48rem) { /* 768px */
      body {
        font-size: 1.25rem; /* 20px */
      }
    }

Vertical Rhythm in Typography

Maintain vertical spacing with rem.

h2 + * {
      margin-block-start: 0.5rem;
    }

    p + * {
      margin-block-start: 1.5rem;
    }

SVG Scaling

Use rem for consistent SVG sizes.

svg {
      width: 5rem; /* 80px if root font-size is 16px */
      height: 5rem;
    }

Layout Measurements

Use rem for consistent layout dimensions.

.container {
      padding: 2rem; /* 32px */
      margin: 1rem auto; /* 16px auto */
    }

Button Sizes

Ensure buttons are scalable and accessible.

.button {
      padding: 0.5rem 1rem; /* 8px 16px */
      font-size: 1rem; /* 16px */
    }

Grid and Flexbox Units

Use rem for consistent grid and flexbox spacing.

.grid-item {
      flex: 1 1 20rem; /* 320px */
      margin: 1rem; /* 16px */
    }

By using rem units, you can easily control the size of all elements on your page by simply changing the root font size. This makes your CSS more maintainable and scalable, and it also ensures that your website is accessible to users who have different font size preferences.

No Comments