Home > OS >  Flex Item only respecting margin or padding when both are set
Flex Item only respecting margin or padding when both are set

Time:11-21

I'm currently exprimenting with CSS a bit, and I'm having an issue where a flexbox item is not respecting margin and padding correctly, and the only way to get a margin on the right side.

Here's the minimal reprodution I was able to come up with:

<body>
    <div class="flexbox">
        <div class="elem">
            This is an element that does not have to be fullwidth.
        </div>
        <div class="elem" style="width: 100%;">
            This is an element that does not have to be fullwidth.
        </div>
    </div>
</body>

<style>
    .flexbox {
        padding: 2rem;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        box-sizing: border-box;
    }
    .elem {
        margin-top: 1rem;
        padding: 2rem;
        background-color: aqua;
    }

</style>

And here is the visual: Repro contents

Please note the following:

  • I have to use width:100%, as it is defined by the framework.
  • Using align-self:stretch works fine, but I do not have a way to do this

Thanks in advance :)

CodePudding user response:

You also have to write box-sizing for the elem class as well. Due to the dimension of the elements that include padding and maybe borders in future. Because box-sizing property allows us to include the padding and border in an element's total width and height. I hope it helped :)

CodePudding user response:

I fixed your problem by solving a couple of small problems:

* {
    margin: 0;
    padding: 0;
}

.flexbox {
    padding: 2rem;
    display: flex;
    width: 100%;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    gap: 10px;
}

.elem {
    padding: 2rem;
    width: 600px;
    background-color: aqua;
}

Html stays the same, I only removed the style= in the element itself

  • Related