CSS3 background image placement
In the process of creating a simple placeholder page, I declare a new website. The page consists of only
- image centered in the center of the logo
- the catch phrase directly below this image
I thought this would be easy - I put a positioned background image with the specified size and then place an absolutely positioned heading h1
to get a "catch phrase" right below the background image.
*
{
color:white;
font-family:arial;
margin:0 !important;
padding:0 !important;
}
body
{
background-color:black;
background-origin:border-box;
background-image:url('https://unsplash.it/1064/800');
background-size:auto 25%;
background-position:center 37.5%;
background-repeat:no-repeat;
height:100vh;
}
h1
{
text-align:center;
position:absolute;
top:62.5%;
right:0;
left:0;
}
<h1>CSS3 is Cool!</h1>
This works to understand that
- background-origin: box border;
-
background-position:center 37.5%
from -
background-size:auto 25%
will be
enter image with
- The background image is horizontally centered with the top-left corner at 37% of the height of its container (set to
100vh
) - The absolutely positioned element
h1
is at (37.5 + 25)% of the top
For good measure, I set padding:0
and margin:0
on everything. However, the end result isn't quite as expected - there h1
is still too much space between the bottom of the logo and the top of the header . It is clear that I am misunderstanding some aspects of background positioning and / or sizing here. I would be greatly indebted to anyone who could put me on the right track
source to share
When using percentages for background images, it doesn't work at all as soon as you think.
When you set the position of the background using a percentage, that positions the image such that the X% of the path by itself is aligned with the X% of the path through the element. This article on CSS Tricks shows it pretty well: percentage-background-position-works
Use viewport height units vh
instead
*
{
color:white;
font-family:arial;
margin:0 !important;
padding:0 !important;
}
body
{
background-color:black;
background-origin:border-box;
background-image:url('https://unsplash.it/1064/800');
background-size:auto 25%;
background-position:center 37.5vh;
background-repeat:no-repeat;
height:100vh;
}
h1
{
text-align:center;
position:absolute;
top:62.5vh;
right:0;
left:0;
}
<h1>CSS3 is Cool!</h1>
source to share