如何使背景图片的宽度居中?

3

无论我尝试什么,我似乎都不能完全控制背景图像的宽度和高度。

为什么我的背景位置:center不起作用?

.full-page-container {      background:url(https://files.pitchbook.com/website/images/content/Midwest.png) center no-repeat;
  height: 100vh;
  width: 80%;
  background-position: center;
}
<div class="full-page-container">
  <div class="heading-wrapper">
    <h1 id="title">Heading Title</h1>
    <p id="description">Header description</p>
  </div>

  <div class="form-wrapper">
    <form id="survey-form">
      <div class="name-wrapper">
        <label for="name" id="name-label">First Name</label>
        <input type="text" id="name" placeholder="First Name" required>
      </div>
    </form>
  </div>


background-size可能是你正在寻找的东西?https://developer.mozilla.org/zh-CN/docs/Web/CSS/background-size - G-Cyrillus
如果您定义了固定高度,则可以同时固定宽度而不会破坏纵横比。Contain将保持宽高比并创建空白区域,而Cover也将保持宽高比但被裁剪。或者您可以使用fill,但是纵横比将被破坏并且图像将被拉伸/压缩。 - tacoshy
Object-fit:fill也不能按预期填充高度和宽度。 - Elizabeth
谢谢,我会插入一张图片让您看到问题。 - Elizabeth
有什么想法为什么我现在居中有问题吗?我改成像素并且对高度和宽度进行了一些控制,我尝试了background-position:center;并在background-size上设置了center; - Elizabeth
显示剩余3条评论
2个回答

2
你可以使用 background-size 来改变大小。实际上,你可以为其设置两个值,如下所示:
background-size: x y;

其中x代表宽度,y代表高度。

因此像这样:

.full-page-container{
   background: url("https://images.unsplash.com/photo-1497581175344-8a5f1a0142a5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=658&q=80");
   background-size: 80% 100vh;
   background-repeat: no-repeat;
   background-position: center;
   height: 100vh;
   width:80%;
}
<div class="full-page-container"></div>

或者这个。

.full-page-container{
   background: url("https://images.unsplash.com/photo-1497581175344-8a5f1a0142a5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=658&q=80");
   background-size: 100% 100%;
   background-repeat: no-repeat;
   background-position: center;
   height: 100vh;
   width: 80%;
}
<div class="full-page-container"></div>


我知道这似乎非常简单,但在实践中你会得到不同的结果。 - Elizabeth
如果你想的话,可以将背景大小设置为100%100%,并通过宽度控制它,如果这是你要寻找的。 - corn on the cob
另一个奇怪的事情是,当我按照你上面写的代码尝试时,它不允许我将图像居中在页面中间。因此,在这种情况下高度是正确的,但宽度无法居中。 - Elizabeth
@Elizabeth 我已经添加了 background-position: center - corn on the cob
让我们在聊天中继续这个讨论 - Elizabeth
显示剩余5条评论

1

那个有点起作用。但它仍然不允许我使用100vh作为高度。它在内容的高度处被截断了。 - Elizabeth
你能否向我解释一下你想要实现什么? - Juraj Revaj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接