2017-03-07 108 views
1

我想在我的网站中添加一个背景图像,该div应该在所有设备上完美调整大小。我尝试了最简单的方法,比如“身高:100%”,但根本不起作用。我也尝试了媒体查询,当然这些查询很有用,但是相当复杂,所以我想问问是否有更简单的方法来解决这个问题。如何根据屏幕尺寸缩放div中的背景图像

这里的HTML

<div class="bg"></div> 

这就是今天的CSS

.bg { 
    background: url('bg.jpg') no-repeat center cover; 
} 
+0

你什么意思 - 设备具有不同的宽高比。 – sol

+0

是的,这是重点。是不是有一种简单的方法让背景图像调整自己独立于设备的屏幕大小? – Timo

+0

我会详细说明...您如何让横向照片以纵向模式在移动设备上进行观看?你想要它覆盖整个屏幕并居中? – sol

回答

1

@Sqnkov有正确的答案。一个空白的div将与设置。

尝试运行下面的代码并参阅。 (制作完整页面并调整浏览器大小)。 center center以Y轴和X轴为中心。 background-size: cover;使图像覆盖所有可用空间。如果你想确保整个图像在视图中,请改用background-size: contain;

body{ 
 
    margin: 0; /* Stripping out margin and padding so .bg can be full width*/ 
 
    padding: 0; 
 
} 
 
.bg { 
 
    box-sizing: border-box; /*Not necessary in this situation*/ 
 
    display: block; /*Not necessary, but we do want it this way*/ 
 
    width: 100vw; /*Not necessary, but we do want it this way*/ 
 
    height: 100vh; /*Necessary. 100vh = 100% of the viewport height*/ 
 
    padding: 0; /* No padding */ 
 
    margin: 0; /* No margins */ 
 
    background: url('https://images6.alphacoders.com/405/405948.jpg') no-repeat center center; 
 
    /* Shorthand: image, repeat, X align, Y align. */ 
 
    background-size: cover; /* Cover all available space*/ 
 
}
<div class="bg"></div>

或者,如果指定的父容器(html, body)的高度和宽度为100%则可以使用100%高度/宽度,而不是100vh/vw.bg容器上如百分数均以相对于父容器。

请参见下面的例子: '?在所有设备上完美地调整'

html, body{ 
 
    margin: 0; /* Stripping out margin and padding so .bg can be full width*/ 
 
    padding: 0; 
 
    width: 100%; /*Setting parent width -- child width is relative*/ 
 
    height: 100%; /*Setting parent height -- child height is relative*/ 
 
} 
 
.bg { 
 
    box-sizing: border-box; /*Not necessary in this situation*/ 
 
    display: block; /*Not necessary, but we do want it this way*/ 
 
    width: 100%; 
 
    height: 100%; /* Now 100% height will work */ 
 
    padding: 0; /* No padding */ 
 
    margin: 0; /* No margins */ 
 
    background: url('https://images6.alphacoders.com/405/405948.jpg') no-repeat center center; 
 
    /* Shorthand: image, repeat, X align, Y align. */ 
 
    background-size: cover; /* Cover all available space*/ 
 
}
<div class="bg"></div>

+0

非常感谢! – Timo

+0

没问题!当你可以运行它时,更容易想象它:D我真的很喜欢,所以让我们嵌入代码片段。无论如何,如果这回答了您的问题,您可以将此标记为已接受答案* wink-wink *; p – StephanieQ

1

只需将大小首选项应用于背景属性。下面是一个速记用法:

这是充满其父到边框的大背景图像的设置。

background: url('images/image.jpg') no-repeat center center/cover;

等于:

background-image: url('images/image.jpg'); 
background-repeat: no-repeat; 
background-position: center; 
background-size: cover; 

我建议给this MDN thread读。

+0

谢谢。但是当我的背景图像在div里面时它有什么不同吗?因为背景仅在**内部有**时才显示,就像文本一样。但是我希望背景图像缩放到独立于屏幕大小,而不管div是否有内容。 – Timo

+0

您是否尝试过上述方法? – snkv

+0

是的,但正如我所说,背景图像是在一个div内。这有什么区别吗? – Timo

1

我刚刚发现,你可以使用“高度”的确并将其设置为,但不“%”“VH”

height: 100vh; 
+1

您还可以使用'vw'(视口宽度)设置宽度。但是当涉及到页面的其他部分时,'vh'和'vw'都会导致一些不想要的行为。 – snkv

+0

好吧,不知道,并会继续关注它。但它不适用于'%'或'px'。有没有其他的单位不会有什么麻烦? – Timo