CSS Height, Width and Max-width

Welcome to the CSS Height, Width, and Max-width tutorial on codeswithpankaj.com. In this tutorial, we will explore how to set dimensions for elements using CSS properties such as height, width, and max-width.

CSS Height Property

The height property sets the height of an element.

Example:

div {
    height: 200px;
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CSS Height - codeswithpankaj.com</title>
    <style>
        div {
            height: 200px;
            background-color: lightblue;
        }
    </style>
</head>
<body>
    <div>This div has a height of 200px.</div>
</body>
</html>

CSS Width Property

The width property sets the width of an element.

Example:

div {
    width: 50%;
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CSS Width - codeswithpankaj.com</title>
    <style>
        div {
            width: 50%;
            background-color: lightgreen;
        }
    </style>
</head>
<body>
    <div>This div has a width of 50% of its parent container.</div>
</body>
</html>

CSS Max-width Property

The max-width property sets the maximum width an element can have, preventing it from exceeding a specified width.

Example:

div {
    max-width: 600px;
    width: 100%;
    background-color: lightcoral;
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CSS Max-width - codeswithpankaj.com</title>
    <style>
        div {
            max-width: 600px;
            width: 100%;
            background-color: lightcoral;
            padding: 20px;
        }
    </style>
</head>
<body>
    <div>This div has a maximum width of 600px and adjusts its width based on the parent container.</div>
</body>
</html>

Practical Examples

Example 1: Setting Fixed Height and Width

img {
    height: 300px;
    width: 400px;
}

Example 2: Using Max-width to Ensure Responsiveness

.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

Conclusion

Understanding and using CSS height, width, and max-width properties allows you to control the dimensions and responsiveness of elements on your web page effectively. By mastering these properties, you can create layouts that adapt to different screen sizes and devices. Stay tuned to codeswithpankaj.com for more tutorials and web development tips!

Last updated