更新时间:2022-10-19 13:47:20
在背景图像中使用百分比时,乍一看根本不起作用.
当您使用百分比设置背景位置时,图像的位置应使其跨自身的X%与跨元素的X%对齐. CSS Tricks上的这篇文章很好地展示了它: percentage-background -position-works
改为使用视口高度单位vh
*
{
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>
I am in the process of creating a simple placeholder page to announce a new website. The page consists of nothing other than
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-position:center 37.5%
with background-size:auto 25%
would yield an image with
100vh
)h1
element is at (37.5 + 25)% from the topFor 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
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>