首页 > 解决方案 > 为什么使用 CSS 无法正确显示图像?

问题描述

我是学习 Web 开发的新手,尤其是 PHP 和使用 CSS。我的图像有 2560 × 1600。这个尺寸已经足以完全覆盖你的背景了吗?我只打算放 1 张背景图片,但是当我运行代码时,它会显示为好像有 2 张图片。

下面是我的输出片段。

在此处输入图像描述

这是我的 CSS 代码:

body{
    margin: 0;
    padding: 0;
    text-align: center;
    background: linear-gradient(rgba(0, 0, 50, 0.5),rgba(0, 0, 50, 0.5)), url(images/wp2330460.jpg);
    background-size: cover;
    background-position: center;
    font-family: sans-serif;
}

标签: phpcss

解决方案


如果您的背景大小设置为覆盖它不应该重复。但是,如果容器大于图像并且 background-size 设置为适合它将重复,除非 background-repeat 设置为no-repeat

无论如何,这里的代码显示了如何首先故意重复你的图像。然后就不要再重复了。

body {
  font-size: 18px;
}
h1 {
  font-family: 'Helvetica Neue', Arial;
  color: #ffffff;
  font-size: 2.5rem;
  line-height: 4.5rem;
}
.background-repeat {
    margin: 0;
    padding: 0;
    height: 2000px;
    text-align: center;
    background: linear-gradient(rgba(0, 0, 50, 0.5),rgba(0, 0, 50, 0.5)), url(https://i.stack.imgur.com/kuEMz.jpg);
    background-size: fit;
    background-position: center;
    font-family: sans-serif;
    background-repeat: repeat;
}

.background-no-repeat {
    margin: 0;
    padding: 0;
    height: 2000px;
    text-align: center;
    background: linear-gradient(rgba(0, 0, 50, 0.5),rgba(0, 0, 50, 0.5)), url(https://i.stack.imgur.com/kuEMz.jpg);
    background-size: fit;
    background-position: center;
    font-family: sans-serif;
    background-repeat: no-repeat;
}
<div class="background-repeat">
  <h1>This Background Image will Repeat</h1>
</div>

<div class="background-no-repeat">
    <h1>This Background Image will NOT Repeat</h1>
</div>


推荐阅读