I am facing an issue while using background-position
in a div alongside background-size: cover
. There appears to be some discrepancies in the browser's calculations, so I am seeking a reliable method to address this.
Further details...
The primary focus is on visual aesthetics and ensuring that all elements scale appropriately within the interface. In previous experiences, utilizing rem or em units for styling has yielded positive outcomes.
Upon initialization or screen size adjustments, I evaluate the available space and dynamically set a suitable font-size
on the container as demonstrated below:
const size = calculateSize();
$("#container").css({fontSize: size + 'px'});
Generally, this approach works effectively, allowing elements to scale and position correctly. However, a recent addition of a graphic button – styled with a background image – introduced a minor yet bothersome flaw.
.button {
background-image: url("img/button.png");
background-size: cover;
width: 10em;
height: 4.5em;
cursor: pointer;
}
.button:hover {
background-position-x: -100%;
}
While experimenting with background-position-x: -10em
, I leaned towards percentage notation due to its adaptability when resizing the button image. Yet, upon hovering over the button, a slight movement is noticed, with the displacement varying based on available space - a phenomenon observed across Chrome, Firefox, and Edge browsers.
While seemingly insignificant, this anomaly sparks curiosity if others have encountered similar behavior and devised solutions. One plausible fix could involve employing distinct images for various button states, albeit I prefer minimizing image count.
UPDATE: After creating two separate images and adjusting the CSS accordingly...
.button {
background-image: url("img/button0.png");
background-size: cover;
width: 10em;
height: 4.5em;
cursor: pointer;
}
.button:hover {
background-image: url("img/button1.png");
/* background-position-x: -100%; */
}
This modification negated the wobble effect, hinting at a peculiar interpretation issue concerning background-position-x
by browsers. Given the subtle nature of the motion, it likely stems from rounding errors.
Minimal, Reproducible Example:
To validate observations, a jsFiddle demonstration highlighting the issue was prepared...
https://jsfiddle.net/xtempore/nfLh86sm/8/
A simplified version of the button image was used, exhibiting black and pale grey hues split down the middle across four divs each configured with varying font-size
settings.
Upon hovering, a color transition should occur, notably noticeable on the first and third divs. Conversely, unexpected residue emerges on the second and fourth divs' left edge during hover actions, particularly prevalent with odd-numbered pixel values and decimals in font-size
measurements.