How to get screen/viewport width in CSS CSS
There are a couple of reasons why you might want to get the width of a user's screen/viewport in CSS. You might want to use the screen/viewport width to determine the size of an element relative to the size of the viewport, or you might want to check the screen/viewport width and apply changes to styles only for users with a viewport larger or smaller than a specific value.
CSS vw units
If you want to size an element relative to the width of the user's screen/viewport, you can use the viewport width (vw) unit and viewport height (vh) unit.
100% of the screen width is written as
100vw. This means that any percentage of the width like 50% would be written as
50vw. You can use vw units anywhere you use other units like pixels (px), such as the width or height of an element, its margin, padding etc.
CSS Percentage units
You can also use percentage units to size elements relative to the viewport width such as
50% for 50% of the viewport width, but this only works if the parent element is allowed to span the full width of the viewport.
Block level elements like
div take up 100% of their parent element's width by default. If the parent element is not the full width of the viewport, then a width of 50% for any child element will mean the element is set to the 50% of the width of the parent element.
CSS media queries
If you want to check the screen/viewport width and make changes to your styles based on the width of the user's screen/viewport, you can do this with CSS
For example, you could write a
min-width media query to check if the viewport is 900px or wider and then write styles inside that media query that only apply for users whose screen/viewport width is at least 900px wide.
/* styles go here */
You can also do the opposite and check for screen/viewport widths smaller than a specified value with the
max-width media query. Styles inside this media query will only apply for users whose screen/viewport width is 900px or smaller.
/* styles go here */
Changing styles based on the user's window/viewport width allows for responsive web design.
Thanks for reading.
Published on 12 Jul 2022