htmlcssflexboxalignmentweb-frontend

Align section heading with the first content item instead of centering in Flexbox layout


I'm working on a section layout where I have a headline and a content container using Flexbox to center the content horizontally. The content container holds several media cards.

<section>
    <h2 class="section-headline">Section Headline</h2>
    <div class="section-content" style="display: flex; justify-content: center; gap: 20px;">
        <div style="border: 1px solid black;">
            <h3>Media Card 1</h3>
        </div>
        <div style="border: 1px solid black;">
            <h3>Media Card 2</h3>
        </div>
        <div style="border: 1px solid black;">
            <h3>Media Card 3</h3>
        </div>
    </div>
</section>

The issue I'm facing is that the headline should align with the start of the first content item (the first media card), but I don't want to center it within the section itself. How can I align the headline to match the start of the first media card (see the following screenshot) instead of centering it with the content? result of the code

I've already tried adjusting the margins, but it doesn't seem to give me the desired responsive result. Is there a Flexbox-based solution or a simple CSS approach that can achieve this?

Any suggestions would be appreciated!


Solution

  • If I understood your assignment correctly:

    .section {
        display: flex;
        justify-content: center; /* Centers the entire section horizontally */
        padding: 20px;
    }
    
    .section-container {
        display: flex;
        flex-direction: column;
        align-items: flex-start; /* Aligns the headline with the content */
    }
    
    .section-headline {
        margin-bottom: 10px; /* Space between the headline and the media cards */
    }
    
    .section-content {
        display: flex;
        justify-content: flex-start;
        gap: 20px;
    }
    
    .media-card {
        border: 1px solid black;
        padding: 10px;
        width: 200px; /* Adjust based on design */
    }
    <section class="section">
        <div class="section-container">
            <h2 class="section-headline">Section Headline</h2>
            <div class="section-content">
                <div class="media-card">
                    <h3>Media Card 1</h3>
                </div>
                <div class="media-card">
                    <h3>Media Card 2</h3>
                </div>
                <div class="media-card">
                    <h3>Media Card 3</h3>
                </div>
            </div>
        </div>
    </section>