Geek Slack

Introduction to CSS
    About Lesson



    CSS Layout – Horizontal & Vertical Align


    CSS Layout – Horizontal & Vertical Align

    Aligning elements horizontally and vertically is a common task in web design. This chapter covers different techniques to achieve horizontal and vertical alignment using CSS.

    1. Horizontal Alignment

    To center elements horizontally, you can use the text-align property for inline elements or margin: auto for block elements.

    Example 1: Centering Inline Elements with text-align

    <div class="box" style="text-align: center;">
        <span>Centered Text</span>
    </div>
    Centered Text

    Example 2: Centering Block Elements with margin: auto

    <div class="horizontal-center">Centered Block</div>
    
    <style>
    .horizontal-center {
        display: block;
        margin: 0 auto;
        width: 50%;
        background-color: #ffccbc;
        text-align: center;
        padding: 20px;
    }
    </style>
    Centered Block

    2. Vertical Alignment

    To center elements vertically, you can use different techniques like flexbox or CSS grid.

    Example 1: Centering Vertically with Flexbox

    <div class="vertical-center">
        <div>Vertically Centered</div>
    </div>
    
    <style>
    .vertical-center {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 200px;
        border: 2px solid #333;
    }
    .vertical-center div {
        background-color: #ffccbc;
        padding: 20px;
    }
    </style>
    Vertically Centered

    3. Both Horizontal and Vertical Alignment

    To center elements both horizontally and vertically, flexbox is one of the most effective methods.

    Example: Centering Both Horizontally and Vertically with Flexbox

    <div class="both-center">
        <div>Centered Both Ways</div>
    </div>
    
    <style>
    .both-center {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 200px;
        border: 2px solid #333;
    }
    .both-center div {
        background-color: #b3e5fc;
        padding: 20px;
    }
    </style>
    Centered Both Ways

    Conclusion

    Aligning elements both horizontally and vertically is crucial for creating well-balanced and visually appealing web layouts. Techniques like margin: auto for horizontal alignment and flexbox for vertical alignment offer powerful and flexible solutions for web designers.