Responsive Design
The above is not true for images though. They will overflow on screen sizes smaller than the image itself. To fix that, the following CSS can be added:
We’re using max-width
and not width
because we want the image to be in its
original size when possible and shrink down to 100% only when the screen is too
small.
Units
em and rem are essential for responsive design. We do not use absolute
units, like cm
, because their size is constant no matter the distance that we
look at the screen. The desktop and phone displays need different sizes of
elements due to that distance.
em and rem
em
The unit applied to an element is about:
- its parent’s
font-size
when dealing withfont-size
. - its own
font-size
when dealing with other properties (e.g.margin
). It is useful, because the things like margin/padding usually should get bigger as the text of the element gets bigger (e.g. a button)
Ems are compounding. If some parent element has 2em
size, and the child has
2em
as well, the result will be that the parent will have 32px, and the child
will have 64px (assuming that it was the default, base size).
rem
rem is similar to em, but it’s relative to the root element of the page
(<html>
) instead of the parent.
Rems are not compounding, they always relate to the root element, making it easier to predict the outcome.
The em/rem are useful when using media queries. Especially rem allows us to
change the font-size
of the <html>
element and impact all the elements that
use rem predictably.
Ems, with their compounding characteristic, can get out of control, as the elements might grow uncontrollably.
Viewport Units
The viewport units (vh, vw) act as a percentage of the browser window.
For example, the 100vh
will take up the whole height of the browser
(responsively). It is used on some pages where we scroll and discover different
sections, each one taking the 100vh
.
vmin and vmax
vmin and vmax work in a way that the final size is dictated by the height or width of the viewport. Whichever is smaller/bigger will be taken as a base.
For example, with 20vmin
, the size of the element will be 20% of the height of
the viewport, or width, depending on which one is smaller at the moment.
vmax works oppositely and is based on the greater size (width/height) of the
viewport.
It has a good effect on titles, which will scale depending on the size of the screen. It’s not good for accessibility though.
Tips
- it rarely makes sense to set
height
of elements. Normally, they should grow as needed. - similarly,
min-width
should be rarely used.