CSS3 background image placement

泄露秘密 提交于 2020-01-04 05:20:14

问题


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% with
  • background-size:auto 25% would

yield an image with

  1. The background image centered horizontally with its top left hand corner at 37% of its container height (set to 100vh)
  2. The absolutely positioned h1element is at (37.5 + 25)% from the top

For good measure I set padding:0and margin:0on 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 h1header. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!