Make text, margin and padding responsive

What is the best practice to make text, margin and padding responsive in a website, I knew there could be different ways to do it, but I wanted to know the best practice that has more benefits and more control over text, margin and padding.
2 Replies
Igor Verve
Igor Verve10mo ago
If you want more control over that stuff then maybe it would make sense to "hard-code" different values for various breakpoints. This would ensure you have strict control over how things appear on particular screen sizes. However, that is not a very efficient way of working. Perhaps more effective way would be to declare dynamic/intrinsic value like Kevin often does in his videos, something like: padding: min(1rem, 3vw); In the example above the padding of an element will be the smallest value out of the 2. So on desktop and other large screens the padding would default to 1rem (aka usually 16 pixels), because that would be smaller than 3vw (which on big screen can be a lot) However as soon as we view our element on smaller screen then padding would be dynamically set by the value of 3vw because on smaller screens 3vw would be smaller than 1rem.
In other words the padding will always be 1rem until screen size becomes small enough where 1rem will be bigger than 3vw, then 3vw will automatically hit in.
13eck
13eck10mo ago
The easiest way to make text, margin, and padding responsive is to use the CSS clamp function to set a sane text size and have the padding/margin use ems so as the font size changes so does the padding/margin. Example:
body {
/* this sets the font size to be anywhere between 1rem and 2rem,
with a change based on the current viewport's width */
font-size: clamp(1rem, 0.25vw + 0.825rem, 2rem);
}

main {
/* main content will always have a least 2em of margin
on the left and right, but be no wider than ~60 characters
which is the suggested max width for legible text
*/
width: min(100% - 4em, 60ch);
margin-inline: auto;
}
body {
/* this sets the font size to be anywhere between 1rem and 2rem,
with a change based on the current viewport's width */
font-size: clamp(1rem, 0.25vw + 0.825rem, 2rem);
}

main {
/* main content will always have a least 2em of margin
on the left and right, but be no wider than ~60 characters
which is the suggested max width for legible text
*/
width: min(100% - 4em, 60ch);
margin-inline: auto;
}
Of course, I'd suggest having a custom property for the font size so you can use your new "rem" more easily:
::root {
--1rem: clamp(1rem, 0.25vw + 0.825rem, 2rem);
--2rem: calc(2 * var(--1rem));
--0.5rem: calc( var(--1rem) / 2);
/* etc…*/
::root {
--1rem: clamp(1rem, 0.25vw + 0.825rem, 2rem);
--2rem: calc(2 * var(--1rem));
--0.5rem: calc( var(--1rem) / 2);
/* etc…*/
As well as potentially having the width/margin above in a utility class (.measure) so you can apply it more selectively. For example, image elements inside the main tag don't need to be limited to 60ch.