问题
I am in the process of creating a simple placeholder page to announce a new website. The page consists of nothing other than
- a centered background logo image
- a "catch phrase" immediately below that image
I thought this would be easy - I place a positioned background image with its size specified and then place an absolutely positioned h1
header to get the "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 is working to the understanding that
- background-origin:border-box;
background-position:center 37.5%
withbackground-size:auto 25%
would
yield an image with
- The background image centered horizontally with its top left hand corner at 37% of its container height (set to
100vh
) - The absolutely positioned
h1
element is at (37.5 + 25)% from the top
For good measure I set padding:0
and margin:0
on everything. However, the end result is not quite as expected - there is still way too much space between the bottom of the logo image and the top of the h1
header. Clearly, I am misunderstanding some aspect of background positioning and/or size here. I'd be much obliged to anyone who might be able to put me on the right track
回答1:
When using percent for background images, it doesn't work at all as one first think.
When you set background position using percent, that positions the image such that X% of the way across itself aligns with X% of the way across the element. This article at CSS Tricks shows it quite 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>
来源:https://stackoverflow.com/questions/44646244/css3-background-image-placement