2014-09-06 55 views
0

我有像这样一个背景图像的横幅:响应式背景图像:如何处理高度?

<section id="banner" class="container" style="background:url(http://placehold.it/1170x200) no-repeat center 
center; background-size: 100% auto; height: 200px;"> 
</section> 

我想有背景图像响应,并相应地调整其高度,但你可以看到,我还设置高度为200像素的初始点让我们可以看到图像。我知道这是不正确的,但我不确定如何将高度设置为'自动',因为只是写“高度:自动”不起作用。

我该如何解决这个问题? Live code here

+0

这取决于你想要的高度相对于做宽度是什么 - 你想保持的长宽比原始图像?你想让它保持相同的高度吗?你想让它受容器大小的指导吗?还是仅仅是为了能够将背景图像作为背景显示的容器? – kinakuta 2014-09-06 04:11:57

+0

好问题。我只是想保持宽高比。不需要相同的高度。是的,容器只是将背景图像显示为背景。 – redshift 2014-09-06 12:03:52

回答

0

根据所需的结果,您可以使用背景属性covercontain
小提琴演示区别CSS Background Cover vs Contain 区别在于,cover将缩小图像尽可能小,而contain将缩放到尽可能大。正如你想缩放高度,contain应该为你工作。

<section id="banner-contain" class="container"></section> 
<section id="banner-cover" class="container"></section> 

#banner-contain.container { 
    background-image: url(http://placehold.it/1170x200); 
    background-repeat: no-repeat; 
    background-size: contain; 
    -moz-background-size: contain; 
    height: 200px; 
} 
#banner-cover.container { 
    background-image: url(http://placehold.it/1170x200); 
    background-repeat: no-repeat; 
    background-size: cover; 
-moz-background-size: cover; 
    height: 200px; 
} 

参考:https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

0

难道是这样的:

<section class="container"> 
    <img class="test" src="http://placehold.it/1170x200"> 
</section> 

.test{ 
    height: auto; 
    margin-right: auto; 
    margin-left: auto; 
    max-width: 100%; 
}