DEV Community

anderu
anderu

Posted on

px, em, rem and percentage in Responsive Design

It is encourage to build website on 'mobile-first' design to optimize the experience of mobile user! To do that we can write base CSS with mobile design first then only use media queries to adjust the layout for wider screens.

There are 4 type of unit we used to adjust the size of element:

  1. Pixels (px): Absolute units that always appear the same size on screen.
  2. em: Relative unit that 1em is equal to the parent element's font-size value. Example if the paragraph have font-size: 20px then if we set the margin-left: 1.5em is equal to 30px of margin-left.
  3. rem: Relative unit that 1rem is always relative to the root element. Example html have font-size: 16px by default, so 1rem = 16px.
  4. Percentage (%): Relative value that % is based on the value of its parent element. Example main have width of 720px, then if we set the child div element width: 80% is equal to 576px.

Which is the best to use? It depend:

  1. px: Pixel is suggest to use on max-width element. Example of div max-width is set to 720px and no matter how big the screen is the max-width still fix on 720px.
  2. em: EM is suggest to use on margin and padding. The margin and padding will then scale based on the element's current font size.
  3. rem: REM is suggest to use on font-sizes element so that there is no compounding issue from em and the font size is known because based on root element which is 16px.
  4. %: Percentage is suggest to use on width especially container and image for size flexibility based on parent element.
  5. Beside the unit suggest above there is unitless number values too. Example of line height property which can be set to value 1 only. 1.5 is suggest to set on line height which is 1.5 times the font-size especially on paragraph.

Another thing to highlight is common breakpoints for responsive design which is:

  • 480px
  • 768px
  • 1024px
  • 1280px

Thanks for your time to finish read about my post. Feel free to share your idea and thought! 😸

let life = {
  first: 'eat',
  second: 'sleep',
  third: 'code',
  forth: 'repeat',
};

const {first, second, third, forth} = life

function capital(word) {
  return word[0].toUpperCase() + word.slice(1)
}

console.log(`${capital(first)}, ${capital(second)}, ${capital(third)}, ${capital(forth)}!`);
Enter fullscreen mode Exit fullscreen mode

Andrew Tan

Top comments (0)