4 tips to write simple CSS

Rmag Breaking News

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>

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
*/

}

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
*/

}

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;
}

My solution

body {
line-height: 1.5;
}

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%);
}

My solution

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

.parent::before {
content: “”;
position: absolute;
}

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;
}

My solution

.container {
margin-block: 1rem 1.5rem;
padding-inline: 1.5rem 1rem;
}

Leave a Reply

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