4 tips to write simple CSS

Stas Melnikov - Mar 24 - - Dev Community

I hear a myth CSS is difficult. I don't agree. I'd like to share my tips about how to write simple CSS.

If you like it you'll get more by subscribing to my newsletter.

:has() and :focus-within remove fragility of the next-sibling combinator

The next-sibling combinator has one disadvantage. It's broken if the order of elements is changed. The reliable alternative is has() and :focus-within πŸ”₯

<div class="cb">
  <input id="cb" type="checkbox" class="cv__input">
  <label for="cb" class="cb__label">Remember</label>
</div>
Enter fullscreen mode Exit fullscreen mode

Some solution

.cb__input:checked + .cb__label::before {
  /*
    styles of the custom checkbox are here
  */
}

.cb__input:focus + .cb__label::before {
  /*
    styles of the custom checkbox are here
  */
}
Enter fullscreen mode Exit fullscreen mode

My solution

.cb:has(:checked) .cb__label::before {
  /*
    styles of the custom checkbox are here
  */
}

.cb:focus-within .cb__label::before {
  /*
    styles of the custom checkbox are here
  */
}
Enter fullscreen mode Exit fullscreen mode

The power of CSS inheritance when defining line-height

Folks, I messed up. I forgot I can use CSS inheritance and add line-height to <body> instead of adding it to <p>, <h*>, <ul>, et al. separately πŸ˜‰

Some solution

p {
  line-height: 1.5;
}

ul {
  line-height: 1.5;
}
Enter fullscreen mode Exit fullscreen mode

My solution

body {
  line-height: 1.5;
}
Enter fullscreen mode Exit fullscreen mode

It’s time to use a new way for centering elements with position: absolute

Do you still use the old snippet to the center element with position: absolute using transform(-50%, -50%)? It’s time to use a new alternative! Meet place-items: center πŸ˜‰

Some solution

.parent {
  position: relative;
}

.parent::before {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
Enter fullscreen mode Exit fullscreen mode

My solution

.parent {
  display: grid;
  place-items: center;
}

.parent::before {
  content: "";
  position: absolute;
}
Enter fullscreen mode Exit fullscreen mode

We don't need to use 0 anymore to define margins and paddings

I had to make a not logical thing, i.e. use 0 to define margins, paddings with opposite sides πŸ˜’ Now margin-block, margin-inline, padding-block, padding-inline help us to make the same without 0 πŸ₯³

Some solution

.container {
  margin: 1rem 0 1.5rem;
  padding: 0 1rem 0 1.5rem;
}
Enter fullscreen mode Exit fullscreen mode

My solution

.container {
  margin-block: 1rem 1.5rem;
  padding-inline: 1.5rem 1rem;
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . .
Terabox Video Player