How does negative margins work

I want half the grey column to be in the blue area and want the column to also extend beyond the bottom boundary of the grid. I used margin-block: -50% but it doesn't work. Why is it not working and what's the right way to do it? https://codepen.io/ksblupzi-the-solid/pen/qEbNQVN
9 Replies
Chris Bolson
Chris Bolson2mo ago
In what way does it "not work"? When I un-comment your margin-block the grey block extends into the blue area and below the bottom.
No description
Chris Bolson
Chris Bolson2mo ago
As to how negative margins work, the confusion might be that, despite what you might expect, when using percentages for the units, the calculation is done based on the inline size (which in this case is the width but this does depend on the writing mode ) of the element, not the block size.
سمية
سميةOP2mo ago
That's it. I didn't notice that the percentage was based on width. I want the margin to be 50% of the height. How can I do that? I figured out how to do it with rems but I'm not sure if this is the right way.
Chris Bolson
Chris Bolson2mo ago
In your Codepen you have a fixed height of 100px so in this case you can just define the margin as -50px. However I do realize that that is just demo and you won’t necessarily have a fixed height value.
MarkBoots
MarkBoots2mo ago
yea, if you want to use percentages, that wont work on the element itself. in that case using a peseudo element might be easier. If its only for the background.
.oversize {
position: relative;
isolation: isolate;
&::after {
content: "";
position: absolute;
inset: -50% 0;
z-index: -1;
background: grey;
}
}
.oversize {
position: relative;
isolation: isolate;
&::after {
content: "";
position: absolute;
inset: -50% 0;
z-index: -1;
background: grey;
}
}
MarkBoots
MarkBoots2mo ago
No description
سمية
سميةOP2mo ago
Is isolate similar to z-index? Are there any differences between them?
MarkBoots
MarkBoots2mo ago
no it creates a new stacking context. in this case it prevents the pseudo to go behind other elements on the same layer. You can see when you remove it, the peusdo will go behind the blue as well with the z-index: -1
سمية
سميةOP2mo ago
I see. It isolates the z indices of the children right? The z-index of a child will not be compared to other elements and be stacked accordingly. It will only be compared with the parent and other siblings.

Did you find this page helpful?