2016-06-28 130 views
1

我有一个800x480像素的背景图像。当我的元素具有固定的大小时,我会看到背景图像,但不是元素具有相对大小或最大宽度时。CSS:元素的相对大小使背景图像消失

工作CSS脚本

.audio-container, .settings-container { 
    max-width:800px; 
    height:480px; 
    position:absolute; 
    background-image:url("../../public/images/Audio/I_Audio_BGK.png"); 
    background-repeat: no-repeat; 
    background-size: 100% 100%; 
} 

CSS与没有显示出背景图片脚本

.audio-container, .settings-container { 
    width:100%; 
    /* Same result with max-width */ 
    height:100%; 
    position:absolute; 
    background-image:url("../../public/images/Audio/I_Audio_BGK.png"); 
    background-repeat: no-repeat; 
    background-size: 100% 100%; 
} 

我能做些什么来显示背景图片尚未有该元素尺寸相对于浏览器窗口?

按要求,这里有父母的DIV

<div ng-controller="MainController" class="main-guy"> 
    <div class="screen-inside"> 
     <div class="audio-container" ng-controller="AudioController"> 
     </div> 
    </div> 
</div> 

这里是父DIV + CSS样式

.main-guy { 
    position:absolute; 
/* Same result if width and height are set to a fixed number */ 
    width: 100%; 
    height: 100%; 
    margin: auto; 
} 
.screen-inside { 
    margin:auto; 
    position:relative; 
    height:60%; 
    width:66.66%; 
} 
+0

请附上您的HTML代码,以帮助证明这个问题。在你的第二个(非工作)例子中,哪一个祖先决定宽度/高度?即什么是100%? – showdev

+0

将'position:absolute'改为'position:relative'它会起作用。 –

+0

@ M.Tanzil谨慎解释原因? – showdev

回答

1

你必须在.settings-containerposition:absolute更改为position:relative为你的形象在这种情况下充当Child.settings-container和图像应根据其父。所以Position:absolute将无法​​正常工作。

检查片段

.main-guy { 
 
    position:absolute; 
 
    width: 100%; 
 
    height: 100%; 
 
    margin: auto; 
 
    background:#999; 
 
} 
 
.screen-inside { 
 
    margin:auto; 
 
    position:relative; 
 
    height:60%; 
 
    width:66.66%; 
 
    background-color:blue; 
 
} 
 

 
.audio-container, .settings-container { 
 
    width:100%; 
 
    /* Same result with max-width */ 
 
    height:100%; 
 
    background-image:url(http://reservations.life/css/images/bg-01.jpg); 
 
    background-repeat: no-repeat; 
 
    background-size: cover; 
 
    position:absolute; 
 
}
<div ng-controller="MainController" class="main-guy"> 
 
    <div class="screen-inside"> 
 
     <div class="audio-container" ng-controller="AudioController"> 
 
     </div> 
 
    </div> 
 
</div>

1

使用下面的HTML:

<div class="settings-container"></div> 

用下面的CSS:

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

.settings-container { 
    width: 100%; 
    height: 100%; 
    text-align: center; 
    background-image: URL("your-image-here"); 
    background-repeat: no-repeat; 
    background-size: cover; 
} 

背景占用视口宽度和高度的100%。很难正确地解决你的问题而不能看到整个图像,但我的猜测是你需要在文档的其他地方应用height

您也可能会遇到使用position: absolute的问题,但这在很大程度上取决于您如何将其应用于您的网站/应用程序/无论如何。