DEV Community

Cover image for CSS Best Practices
Bernie January Jr.
Bernie January Jr.

Posted on • Edited on

CSS Best Practices

How does CSS work:

Cascading Style Sheets (CSS) is unique amongst the programming languages. Knowing why it works the way it does may help in understanding why it's sometimes difficult to wrangle. Credit goes to Miriam Suzanne for my better general understanding of it.

The web, specifically the network of HTML documents we call the web, was created to be device agnostic, which just means that anyone on any device can view web HTML documents. In other words, the client-side (a website end user) controls the display of our webpage. Think different devices: phones, tablets, desktop computers, different browsers, different settings, and different user needs: screen readers, assistive devices, etc. A webpage or application today must be adaptive and shape shift to fit the shape of our users client-side customizations.

The ‘Cascade’ in CSS takes all of these sources of information and defines a set of rules for how our web presentation renders in the browser. So when writing CSS, you’re sort of suggesting how output SHOULD look on an end user’s screen. It’s very different than designing for print, where we dictate the exact output of what our end user sees and receives. CSS can seem to act weird because it is resilient and adaptive by design. When CSS attributes fail, the browser is told to ignore them. CSS is an optional decorator for which parts can and intentionally fail to preserve our webpage’s content.

Reset CSS:

We all know that CSS has more than a few weird quirks that can feel buggy and slow down your workflow. We can get around some of these ‘bugs’, by what many call a CSS reset.

The most notable CSS reset is probably this one created by Eric Meyers some years ago. I found out about this reset through another CSS legendary resource: Kevin Powell. If you want to learn more about CSS, I definitely recommend checking out his YouTube channel.

For me… the Meyer’s reset is a bit wordy and exceeds the needs of my projects. I cherry-pick the resets that I utilize most here:

margin: 0 for everything.

/* resetting CSS margin: remove default margin on text tags */
* {
  margin: 0;
}

Enter fullscreen mode Exit fullscreen mode

box-sizing: border-box tells the browser to account for any border and padding in the values you specify for an element's width and height.

/*
  Use a more-intuitive box-sizing model.
*/
*,
*::before,
*::after {
  box-sizing: border-box;
}
Enter fullscreen mode Exit fullscreen mode

font: inherit: I hate having to deal with the default fonts for button, input, textarea, and select elements. You can fix this by having it inherit whatever font you set your body to.

/* remove built-in form typography
margin: remove default margin on text tags
*/
input,
button,
textarea,
select {
  font: inherit;
}
Enter fullscreen mode Exit fullscreen mode

overflow-wrap: break-word: There’s almost never a time when you’d want your text to overflow outside of the container div you place it within.

/*
  Avoid text overflows
*/
p,
h1,
h2,
h3,
h4,
h5,
h6 {
  overflow-wrap: break-word;
}
Enter fullscreen mode Exit fullscreen mode

Organize Your CSS

By organization, I really mean to stress = Consistency. Consistency is everything. It will speed up your workflow, reduce debugging, and make edits easier. And, there are always edits.

  1. It’s best practice to keep unique component css files separate so that you separate your styling logic just as you would your component logic: app.css, sidebar.css, navbar.css, etc.

  2. Even if you have a single style.css file, be sure to separate global css i.e. css that impacts tags like body, h1, p, etc. and local css i.e. .nav-buttons, #nav-title, #nav-bar… it's best-practice to keep like with like.

  3. Use :root variables for often used styles like color, font-size, and font-family. This makes for easy color look-up/auto fill and worry-free consistency with your design brief and prototype UI.

/* //// ROOT VARIABLES  */
:root {
  --black: #000000;
  --teal: #86FDF1;
  --light-blue: #C9D6EA;
  --violet: #52489C;
  --yellow: #FFD449;
  --white: #F7F3F3;
  --title-font: vollkorn, serif;
  --primary-font: system-ui, sans-serif;
  --secondary-font: Georgia, serif;
  --lg-font: 2.5rem;
  --md-font: 1rem;
  --sm-font: .5rem;
}

/* //// GLOBAL | site-wide */

body {
  background-color: var(--black);
  font-family: var(--primary-font);
}

Enter fullscreen mode Exit fullscreen mode

Comment Your CSS

Create comments in your CSS, trust me…. you or the developer who will update the project in the future will appreciate it.

CSS Comment:
/* This is a CSS comment*/

It’s common convention to add a block of comments between sections of your stylesheet, helping you to differentiate between sections at a glance. If you use a string that won’t appear in your code, you can easily jump from section to section i.e. ////

/* //// ROOT VARIABLES  */

/* //// GLOBAL | site-wide */

/* //// HEADER + NAV  */

/* //// MAIN  */

/* //// FOOTER  */

/* //// MEDIA QUERIES  */
Enter fullscreen mode Exit fullscreen mode

Accessible HTML/CSS:

  1. Follow Title Tag Hierarchy: It's best practice to only have one h1 tag per page and to follow title tag hierarchy h1 > h2 > h3 > h4 > h5 > h6 as screen readers and search engines recognize HTML title tags.

  2. Alt attributes: Be sure to provide descriptive alt text for all your non-decorative images. Individuals that require or prefer to use screen readers to traverse your website or app will have image context and will have better User Experience (UX) with descriptive alt text. It’s also important for Search Engine Optimization (SEO). Generally speaking, creating a more accessible product makes for better UX for all users.

<img id="meme" src="img/viral-meme-squat-squint-woman.webp" alt="A viral meme of a woman squatting and squinting in a stylish pink blazer, gold hoop earrings, and heels trying to figure out why you didn't place ALT text in your image tag"/>
Enter fullscreen mode Exit fullscreen mode
  1. ARIA states and properties: ARIA attributes allow developers a way to modify an element’s states and properties as defined in the accessibility tree. Some of the most common attributes are:
  • aria-label: defines a string value that labels an interactive element. It describes an action that one might expect of a particular element. A button that closes your navigation menu might look like this:
<button aria-label=close on-click=navMenu.close()></button>
Enter fullscreen mode Exit fullscreen mode
  • aria-selected: indicates the current "selected" state for gridcell, option, row and tab roles. If true, the selectable element is selected and when false, vice versa.
<div class="tab-interface">
  <div role="tablist" aria-label="Sample Tabs">
    <span
      role="tab"
      aria-selected="true"
      aria-controls="panel-1"
      id="tab-1"
      tabindex="0">
      First Tab
    </span>
    <span
      role="tab"
      aria-selected="false"
      aria-controls="panel-2"
      id="tab-2"
      tabindex="-1">
      Second Tab
    </span>
  </div>

Enter fullscreen mode Exit fullscreen mode

Test Your Media Queries:

Match your media queries to common device dimensions AND TEST IT!
Also, Media Queries always go at the end of the CSS file per convention

@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

Enter fullscreen mode Exit fullscreen mode

Here are typical screen sizes:

/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {...}


/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {...}


/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) {...}


/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px) {...}


/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {...}
Enter fullscreen mode Exit fullscreen mode

For orientation: landscape v. portrait (the default):

@media only screen and (orientation: landscape) {
  body {
    background-color: lightblue;
  }
}

Enter fullscreen mode Exit fullscreen mode

I hope this was helpful. Thanks for reading.

Below is a list of Resources that might continue to be helpful.

Resources

  1. CSS MDN docs: link
  2. Miriam Suzanne's: explanation of why CSS is so weird: link
  3. Eric Meyer's: THE CSS reset: link
  4. Kevin Powell's: Youtube Channel to learn CSS: link
  5. The Box Model MDN docs: link
  6. ARIA attributes MDN docs: link

Top comments (0)