I am using negative margin to cause some playing card elements to overlap, creating a visual effect akin to how a hand of playing cards appear in real life.
The issue here is that the negative margin is defined in vw
. This means that as the screen size widens, the value of a single vw
becomes greater, and the negative margin grows, causing the cards to overlap more. This is contradictory to my intentions-- as the screen widens, the cards should spread accordingly, and overlap more as the screen narrows.
If I instead use an absolute value like px
, the overlap will remain constant as the screen size changes, which is also undesirable.
I have spent many hours trial & erroring this and have yet to come up with a scheme that works correctly.
How can you cause a negative margin to diminish as the screen increases, with CSS or with JS if CSS can't do it alone?
You could combine clamp()
with relative
positioning. You'll probably need to adjust the values a little to make it good looking, but this is the core concept.
:root {
--cardWidth: 200px;
--min: calc(var(--cardWidth) / 8);
--var: 7.5vw;
--max: calc((var(--cardWidth) / 4) * 7);
--overlap: clamp(
var(--min),
var(--var),
var(--max)
);
}
body {
display: grid;
place-items: center;
margin: 0;
}
.w {
display: flex;
}
[class*=card] {
height: 300px;
width: var(--cardWidth);
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 4px -1px #000;
}
.card-2 {
position: relative;
left: calc((var(--cardWidth) * -1) + var(--overlap));
}
<div class="c"></div>
<div class="w">
<div class="card"></div>
<div class="card-2"></div>
</div>