Say Bye To PX When Writing Responsive CSS

wwayne
Yet SH
Published in
2 min readOct 16, 2018

--

When building Yet, I need to think deeper about the responsive, it’s not only about how the website displayed on different devices, but also about how to simulate different devices when user previewing on the desktop.

I managed to avoid using JS and solve the responsive problem only by CSS. Besides using@media I’d like to share some other experiences for building a better responsive website and it’s time to say goodbye to PX.

Using em for font-size, padding and margin

I know there’s a lot of suggestion of using rem for font-size, but using em is more flexible. rem calculates font-size based on the root’s font-size, and em calculates font-size based on its parent-element’s font-size, if no font-size found on parent-element, it will go on searching on parent’s parent till the root, so if you only set font-size on the root, using em is as same as using rem .

More important, rem and em can be used for padding and margin as well, that’s why usingem give you the ability to simulate different devices. Say you have a component called myTemplate and its elements are all set as em , wrapping the component into an element with a specific font-size can render the component to a different size which is useful when you’re implementing features like preview.

<div class='tablet' style='font-size: 10px'>{myTemplate}</div><div class='mobile' style='font-size: 8px'>{myTemplate}</div>

Responsive elements with a specific ratio

Say you have an element which ratio of width to height is 4 to 3, and you want the element always take 30% width of a row, see the following illustration:

Then the HTML and style can be:

flex: 0 0 30% make the item element always take 30% width of the row, we can not set % directly on height, but we can make use of the rule that % in padding and margin always calculated against the width, so we are able to use padding-bottom to fill the element in vertical(3 / 4) * 30% = 22.5%

That’s it

Only using CSS to solve the responsive problem is always preferred, because it is much easier to maintain and have a better performance than using javascript.

--

--