Understanding CSS Height Units

Measuring height while developing a website can sometimes be tricky. It might feel overwhelming or surprisingly easy, depending on the situation. There are various types of measurements in CSS, such as `px`, `vh`, `dvh`, `auto`, and `100%`, used for width and height. Today, I will break down each measurement for height and width to help you understand them with ease.

1. PX (Pixels):

If you set a height of `100px`, the absolute unit fixes the height value. In this example, the height is 100 pixels, regardless of the parent component's size or the viewport size. It remains constant across different screen sizes but does not adapt to all screen sizes.

2. Auto:

This is the default value for the height of an element in CSS. If there is content, the height adjusts according to the content size; otherwise, it shows zero height or adopts the parent's height. This is useful for dynamic viewports when the height value is unknown.

3. 100%:

This is a relative unit of an element's height, equal to 100% of the parent element's height. If the parent element's height is not defined, the child component with `100%` may not render as expected. It allows for flexible layouts that can adapt to different height sizes.

4. 100vh (Viewport Height):

vh stands for Viewport Height. It represents 100% of the viewport height. It will always fill the entire height of the user's screen, regardless of the parent element's height. This is useful for creating full-width background sections or subsections.

5. 100dvh (Dynamic Viewport Height):

Similar to 100vh, dynamic viewport height adapts to dynamic UI elements such as on-screen keyboards or browser address bars. This makes it particularly useful for responsive mobile screens.

Conclusion

Understanding the different units of measurement for height and width in CSS is crucial for creating responsive and adaptive web designs. Each unit has its unique use case, and choosing the right one depends on the specific requirements of your layout. By mastering these measurements, you can ensure that your website looks great on any device, providing a seamless user experience.

0
Subscribe to my newsletter

Read articles from Chaitanya Vankar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Chaitanya Vankar
Chaitanya Vankar

๐Ÿ‘‹ Hi, I'm Chaitanya Vankar, a passionate Front-end developer in JavaScript and TypeScript. Excited to share insights on React JS and other frontend frameworks/libraries.