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;
}
Top comments (4)
Thank you :-)
Thank you for posting.
What if I need to zero out padding and or margins on both axis?
Is it still better to use
margin: 0;
and orpadding: 0;
?Thanks again!
Yeap, it's correct
Thanks for the great post