2017-04-05 82 views
0

我面临一个简单的问题,它占用了我很多时间。通过ID选择器不应用CSS背景图像样式

我有一个简单的CSS的图像定义为背景:

#header-content{ 
    background-image: url("../images/header-img.png"); 
    background-repeat: no-repeat; 
    background-position-x: center; 
    -webkit-background-size: cover; 
    -moz-background-size: cover; 
    -o-background-size: cover; 
    background-size: cover; 
} 

而且DIV具有此ID的HTML页面:

<!-- HEADER --> 
<div id="header"> 
    <div class="container-fluid"> 
     <div class="row"> 
      <div class="col-md-12"> 
       <div id="header-content"> 

       </div> 
      </div> 
     </div> 
    </div> 
</div> 
<!-- HEADER --> 

很简单。但图像没有显示。可能是什么问题呢?

P.S .:图像目录是正确的。

+1

你的问题可能是'#header-content' div没有任何大小。尝试添加:'height:100px;宽度:200px' –

+0

好,工作!但现在图像不是100%宽度。双方都有余地。 – Developer1903

+0

做一些关于CSS –

回答

2

您的问题可能是#header-content div没有任何大小。尝试添加:height: 100px; width: 200px

#header-content{ 
 
background-image: url("http://unsplash.com/photos/1-ISIwuBMiw/download"); 
 
background-repeat: no-repeat; 
 
background-position-x: center; 
 
-webkit-background-size: cover; 
 
-moz-background-size: cover; 
 
-o-background-size: cover; 
 
background-size: cover; 
 
height: 100px; 
 
width: 200px; 
 
}
<!-- HEADER --> 
 
<div id="header"> 
 
    <div class="container-fluid"> 
 
     <div class="row"> 
 
      <div class="col-md-12"> 
 
       <div id="header-content"> 
 

 
       </div> 
 
      </div> 
 
     </div> 
 
    </div> 
 
</div> 
 
<!-- HEADER -->

+0

为什么“width:200px”? – Johannes

+0

@Johannes - 没有理由,任意数字可以让这个例子工作 –

+0

默认情况下它是100%,没有必要定义宽度 – Johannes

1

heightwidth设置为您的#header-content

2

没有必要设置width(用于DOVs默认为100%),但如果你没有在DIV任何内容,你必须为该DIV设置一个height值以查看背景(如果不是,则为0px高=不可见)。

0

此外,在设置高度时,请尝试使用与百分比(%)不同的测量单位,因为百分比有时可能无法正确工作,并且会使其显示效果不佳。您可以使用px或vh。

1

因为您尚未在您的css代码中定义widthheight。 例如,将这些width: 400px; height: 400px;添加到#header-content {}的第一个,它就可以工作。您还可以在不使用widthheight属性的情况下为body或HTML标记执行此操作。