Geek Slack

Introduction to CSS
    About Lesson



    CSS Layout – width and max-width


    CSS Layout – width and max-width

    The width and max-width properties in CSS are used to control the width of elements.

    1. width

    The width property specifies the width of an element.

    Example:

    <div class="box" style="width: 50%;">This box is 50% wide.</div>
    
    <style>
    .box {
        padding: 20px;
        background-color: #ddd;
        margin: 10px 0;
    }
    </style>
    This box is 50% wide.

    2. max-width

    The max-width property specifies the maximum width of an element. The element will not be wider than the max-width value.

    Example:

    <div class="box" style="max-width: 300px;">This box has a max-width of 300px.</div>
    
    <style>
    .box {
        padding: 20px;
        background-color: #ddd;
        margin: 10px 0;
    }
    </style>
    This box has a max-width of 300px.

    3. Combining width and max-width

    You can combine width and max-width properties to create more flexible layouts.

    Example:

    <div class="box" style="width: 80%; max-width: 400px;">This box is 80% wide but no more than 400px.</div>
    
    <style>
    .box {
        padding: 20px;
        background-color: #ddd;
        margin: 10px 0;
    }
    </style>
    This box is 80% wide but no more than 400px.

    4. Responsive Design with max-width

    The max-width property is useful for responsive design because it prevents elements from stretching out too much on large screens while still allowing them to shrink on smaller screens.

    Example:

    <div class="box" style="max-width: 100%;">This box has a max-width of 100%.</div>
    
    <style>
    .box {
        padding: 20px;
        background-color: #ddd;
        margin: 10px 0;
    }
    </style>
    This box has a max-width of 100%.

    Conclusion

    The width and max-width properties are fundamental for creating responsive layouts in CSS. Understanding how to use these properties allows you to control the dimensions of elements effectively.