如何获取包含背景图像以覆盖整个div?

时间:2017-12-19 22:47:14

标签: html css responsive-design

好的,我的问题是如何让我的图像更具响应性?我是一名新编码员,所以我还在努力了解css。我尝试过使用包含值,但它并不涵盖整个div。我也尝试过封面,但是当它在div中扩展时它并没有显示整个图像。如果有人有任何想法,我很乐意听取您的意见。谢谢此外,它与覆盖整个页面的问题不同。我希望图像覆盖在我的div中,并且它似乎无法正常工作。



.tribute {
  margin-top: 40px;
  margin-left: 12%;
  height: 250px;
  width: 35%;
  background: url(dickgregory.jpg);
  background-size: cover;
  float: left;
}

<div id="projects">
    <br>
    <br>
    <h1 class="centerh1">Projects</h1>
    <hr class="portfoliohr">
    <a href="https://codepen.io/boiledbiscuit/pen/dzeMPW?q=dick+gregory&limit=all&type=type-pens" target="blank">
        <div class="tribute">
        </div>
    </a>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您的图片 占用width元素的完整height.tribute。问题是,您已将margin添加到.tribute元素,并限制其width

删除边距并将width设置为100%会显示覆盖整个区域的图像。

请注意,background-size: cover可能会拉伸或裁剪图像,background-size: contain调整图像以确保图像始终可见。

最好通过一个例子证明这一点。

内含:

&#13;
&#13;
.tribute {
  height: 250px;
  width: 100%;
  background: url(http://placekitten.com/310);
  background-size: contain;
  float: left;
}
&#13;
<div id="projects">
  <br>
  <br>
  <h1 class="centerh1">Projects</h1>
  <hr class="portfoliohr">
  <a href="https://codepen.io/boiledbiscuit/pen/dzeMPW?q=dick+gregory&limit=all&type=type-pens" target="blank">
    <div class="tribute">
    </div>
  </a>
</div>
&#13;
&#13;
&#13;

封面:

&#13;
&#13;
.tribute {
  height: 250px;
  width: 100%;
  background: url(http://placekitten.com/310);
  background-size: cover;
  float: left;
}
&#13;
<div id="projects">
  <br>
  <br>
  <h1 class="centerh1">Projects</h1>
  <hr class="portfoliohr">
  <a href="https://codepen.io/boiledbiscuit/pen/dzeMPW?q=dick+gregory&limit=all&type=type-pens" target="blank">
    <div class="tribute">
    </div>
  </a>
</div>
&#13;
&#13;
&#13;

希望这有帮助! :)

答案 1 :(得分:0)

不幸的是,covercontain是处理不是您想要的比例的图像的最佳方式。您可以使用<img>标记而不是带有背景图像的div,如果这样可以使用。否则,我通常会在与图像类似的元素上添加背景颜色,以便更好地融合。

.tribute {
  margin-top: 40px;
  margin-left: 12%;
  height: 250px;
  width: 35%;
  background-image: url('https://upload.wikimedia.org/wikipedia/commons/7/7b/Dick_Gregory.jpg');
  background-size: contain;
  background-position: center center;
  background-repeat: no-repeat;
  background-color: #666;
  float: left;
}
<div id="projects">
  <br>
  <br>
  <h1 class="centerh1">Projects</h1>
  <hr class="portfoliohr">
  <a href="https://codepen.io/boiledbiscuit/pen/dzeMPW?q=dick+gregory&limit=all&type=type-pens" target="blank">
   <div class="tribute">
   </div>
  </a>
</div>