Search code examples
cssflexbox

How do I use the width limit and use gap at the same time?


I have a problem, I need a form that will be limited in width and use the gap.

CodePen

body {
    margin: 0;
    padding: 0;
}

.container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    gap: 18px;

    min-height: 100vh;
}

.container--example {
    background-color: #000;
    width: 100%;
    height: 100px;
}
<div class="container">
    <div class="container--example"></div>
    <div class="container--example"></div>
    <div class="container--example"></div>
    <div class="container--example"></div>
</div>

Here the div is stretched to 100%, the whole screen, I can set the width settings on the element in the container, but then gap will not work. Thank you so much in advance for your answer

Unfortunately, I do not know how to fix this problem, I hope to find the answer here.

UPD: Also, it is possible to put widths on the text and so on, but it's too much of a pain.


Solution

  • Set a padding to the parent of .container, in the example that would be body.

    CSS body { padding: 0 2rem } would create a space of 2rem on either side of .container, which would be true for every child of body.

    With a little math you can even make that space responsive:

    • 16px space on a 320px viewport
    • 256px space on a 1920px viewport

    would yield equation y = 0.15x + 32 using Linear Equation y=mx+b for points p1(320,16) and p2(1920,256).

    body {
        margin: 0;
        /* Using y=mx+b => y = 0.15x + 32 for points p1(320,16) and p2(1920,256) */
        padding: 0 calc(15vw - 2rem);
    }
    
    .container {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    
        gap: 18px;
    
        max-width: ;
        min-height: 100vh;
    }
    
    .container--example {
        background-color: #000;
        width: 100%;
        height: 100px;
    }
    <div class="container">
        <div class="container--example"></div>
        <div class="container--example"></div>
    </div>