Units in css(lt.28)

Units in css(lt.28)

·

2 min read

Introduction:

CSS unit is a measurement of length, which is used to specify the size of element on the website.

Types of CSS Unit

  1. Absolute: They represent a fixed size and remain the same regardless of screen size and are not responsive to changes in font size or viewport size.

  2. Relative: They represent a size that is relative to another reference value. They change according to the various screen sizes.

Most Commonly used CSS units:

  1. px: The most commonly used absolute unit, representing a single pixel on the screen.

  2. em: Depend upon the parent.

  3. rem: Depend upon root. Value of 1rem will be 16 px by default.

  4. percentage: Represents a percentage of a reference value, such as the parent element's width or height

  5. vw: This is a relative unit.Represents a percentage of the viewport's width

  6. vh: This is also a relative unit.Represents a percentage of the viewport's height.

When to choose what to choose:

Use absolute units:

For specifying precise sizes that should remain constant.

When working with fixed layouts.

Use relative units:

For creating a responsive layouts that are flexible too.

When size of one depend upon the size of another element.

code to demonstrate:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>units</title>
    <style>
        section
        {
            border: 2px solid red;
            width: 50vw;
            height: 50vh;
            font-size: 20px;
        }
        main
        {
            border: 2px solid black;
            width: 50vh;
            /* 2 em ka mtlb h ki parent k font size * child ka size given .i.e 2*20,agr 4em hota to 4*20px */
            font-size: 1rem;
        }
    </style>
</head>
<body>
    <section>
        <main>hi how r u</main>
        </section>
</body>
</html>

lt.28:https://hashnode.com/post/clpz4d88y000608l4eg898d6f

Did you find this article valuable?

Support himanshu by becoming a sponsor. Any amount is appreciated!