html - 无论屏幕大小如何,背景图像都适合整个屏幕

标签 html css background background-image

我有一个 <header class="header">在这个 header 标签内,我有导航栏。基本上我通过 header 设置背景图片类所以我可以把剩下的 <body>图片下方的内容。我的页面布局是:

<header class="header">
  <nav>
    navbar content
  </nav>
</header>

<body>
  all the text and images are here in the body
</body>

这是我的 CSS:

html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

.header {
  width: 100%;
  height: 100%;
  margin: auto;
  background: url('../img/background.jpg') no-repeat;
  background-size: cover;
}

问题是,当我在 MacBook Air 上拉取网站时,我的背景图像非常适合并且响应迅速,但当您在 ​​Mac 桌面上拉取我的网站时,图像不适合整个屏幕。我也试过这样做:

.header {
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
}

但这没有用。可能是因为我的图像尺寸?我如何让它适合任何屏幕的整个屏幕,包括大型 Mac 桌面显示器?

最佳答案

如果百分比(%)不起作用,你可以使用vh(view port height)和vw(view port width)来设置背景大小

<!DOCTYPE html>
<html>
<head>
<style>
body  {
    background-image: url("https://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2014/4/11/1397210130748/Spring-Lamb.-Image-shot-2-011.jpg");
    
    background-size: 100vw 100vh;
}
</style>
</head>
<body>

<h1>The background-image Property</h1>

<p>Hello World!</p>

</body>
</html>

关于html - 无论屏幕大小如何,背景图像都适合整个屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48450668/

相关文章:

javascript - Cody Lindley 所说的 "nodes contained in the collection are either literally part of the live document or a snapshot of the live document"是什么意思?

html - 响应式全高两栏网站,一栏内有图片

css - 在 x/html 中编写联系信息的最佳方法是什么?

css - 具有背景颜色的透明背景图像

android - 在 Oreo (8.0.0+) (API 26+) 中,如何在应用程序处于后台或终止时获取位置服务更新

java - 使用 Swing 在 JFrame 上设置背景图像

javascript - iframe 的自动滚动对我不起作用

html - 首先加载低分辨率背景图像,然后加载高分辨率背景图像

CSS 第 n 个子节点,穿过 Twig

javascript - 谷歌地图不会在 div 容器中显示整个 map