I put together a page that has a .floatbox, which sets the top and bottom margin based on the variable --currentViewportHeight (basically, I dynamically detect it with JS and insert it into my CSS, on page load and resize); --autoTopBottomMargin is set arbitrarily to 0.1 because this is how big I want the top and bottom margins to be. The following class allows me to have very nice, dynamic top and bottom margins.
.floatbox {
position: relative;
width: 500px;
left: 50%;
transform: translate(-50%);
margin-top: calc(var(--currentViewportHeight) * 1px * var(--autoTopBottomMargin));
margin-bottom: calc(var(--currentViewportHeight) * 1px * var(--autoTopBottomMargin));
padding-top: 20px;
}
Then, when the size of the viewport becomes less than the the size of .floatbox (with a little wiggle room—600px, to be precise), I go into the responsive spec. 0.00176 determines the perfect relative size and right-hand margin in one go.
@media only screen and (max-width: 600px) {
.floatbox {
position: absolute;
transform-origin: left top;
transform: scale(calc(var(--currentViewportWidth) * 0.00176));
top: calc(var(--currentViewportWidth) * 1px * var(--repositionFactor));
left: calc(var(--currentViewportWidth) * 1px * var(--repositionFactor));
margin-top: unset;
}
}
Here, I use --currentViewportWidth (also detected with JS and inserted dynamically into my CSS) to perfectly scale .floatbox, so it's sized exactly right and with the exactly right margins on any device.
Seemingly, everything is just fine...except, no matter what I do, I cannot set margin-bottom for the responsive spec, by using either static or dynamic values. On mobile, it just sticks to the bottom of the screen.
Update: The plot thickens. It appears that my calculation of --currentViewportWidth doesn't pass the same value in Firefox (where I've been testing mainly) and Chrome. My function is exceedingly simple, and yet the script seems to pass wildly different values into the CSS.
function detectViewport() {
// Calculate the viewport width and pass it into JS and CSS variables
let viewportWidth = window.innerWidth;
document.querySelector(':root').style.setProperty('--currentViewportWidth', viewportWidth);
// Calculate the viewport height and pass it into JS and CSS variables
let viewportHeight = window.innerHeight;
document.querySelector(':root').style.setProperty('--currentViewportHeight', viewportHeight);
}
from Responsive float box loses bottom margin in mobile view, FF and Chrome passing viewport values differently into CSS, and other confounding mysteries
No comments:
Post a Comment