CSS body `background-image` aligned right on Chrome, Safari (webkit)
-
01-07-2021 - |
Frage
I've been struggling with a problem on webkit browsers (chrome & safari) while adapting a website for right-to-left readers (Arabic & Hebrew languages). Finally I reported this as a WebKit bug, but I still need a workaround for this.
The problem
Assign a background image to the body tag, and position this background image to the right and repeat-y. Now, make the window smaller until the horizontal scrollbar appears. The background image will no longer be aligned to the right of the document, it will be positioned x
pixels from the left where x
is the width of the viewport.
Here's a simplified example, isolating the problem. The word "Contents" is expected to always be on top of the blue part of the background image.
<html dir="rtl">
<head>
<style type="text/css">
body {
margin: 0;
background-image: url(data:image/png;base64, ...);
background-position: top right;
background-repeat: repeat-y;
}
#contents {
width: 900px;
height: 900px;
}
</style>
</head>
<body>
<div id="contents">Contents</div>
</body>
</html>
You can also see the screendump included in the WebKit bug report.
Any thoughts?
Lösung
What about using an absolutely positioned element?
<html dir="rtl">
<head>
<style type="text/css">
body {
margin: 0;
}
#bg {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAvgAAAACAgMAAABQ2kAmAAAAAXNSR0IArs4c6QAAAAlQTFRF5ev/9Pb/////KIKAcgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfcCQIMFSrrJQqoAAAAFUlEQVQY02PgWjU4wQoGokDUkHY+ACqhykF2Ey1yAAAAAElFTkSuQmCC);
background-position: top right;
background-repeat: repeat-y;
position: absolute;
right: 0;
width: 100%;
height: 100%;
z-index: -1;
}
#contents {
width: 900px;
height: 900px;
}
</style>
</head>
<body>
<div id="bg"></div>
<div id="contents">Contents</div>
</body>
</html>
Seems to work for me as a workaround.