为什么背景图片在外部CSS中不起作用,而在内部CSS中却起作用?

时间:2020-07-09 19:46:14

标签: html css

首先,我是HTML和CSS的新手,希望您能理解我的知识不足。因此,直截了当我尝试通过外部CSS添加Background-image时遇到了问题,但是很奇怪,它可以在HTML存档中使用。之后,我在这里搜索此问题,发现了很多解决方案,但没有一个起作用,主要是解释了为什么发生此问题。所以,我需要帮助。
如您所见,当我尝试通过CSS加载时,我什至在路径中使用add ..时也很注意,但这没有用。

整个目录组成如下:


    |part1|
         |css|
             style.css
         |images|
             header_bg.png
             logo.png
         |js|
            there's nothing here till the current moment
         index.html 

-HTML代码:

<!DOCTYPE html>
<html>
</head>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <meta charset="utf-8">
    
    <style type="text/css">
        .container_banner{
            width: 100%;
            height: 557px;
            background-image: url("images/header_bg.png");
        }
    </style> 
</head>

<body>
    <div class="header">
        <div class="center">
            <img src="images/logo.png">
        </div><!-- close the div center-->
        
    </div><!-- close the header-->
    
    <div class="container_banner">
        <div class="center">
            
        </div><!--close the div center-->
    </div><!--close the container-banner-->
</body>
</html>

-我的CSS:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}


.center{
    width: 1280px;
    margin: 0 auto;
}

.header{
    width: 100%;
    height: 60px;
    background-color: #212343;
}
 .header img {
    margin: 19px;  
 }

 .container_banner{
    width: 1280px;
    height: 800px;
    background-image: url("..images/header_bg.png");
 }

2 个答案:

答案 0 :(得分:0)

任何外部CSS样式表文件都将查找相对于其自身URL的图像(如果其中包含相对URL)。示例:

http://www.external-website.com/css/style.css包含:

background-image: url("images/header_bg.png"); /* This will reference http://www.external-website.com/css/images/header_bg.png */

因此,如果您网站的URL是http://my-website.com/,并且您要在其中插入http://www.external-website.com/css/style.css,请不要指望该外部CSS文件中的相对URL指向http://my-website.com/资源(在这种情况下,图像)。

答案 1 :(得分:0)

 .container_banner{
    width: 1280px;
    height: 800px;
    background-image: url("../images/header_bg.png");
 }

/ ..是与/ images相同的文件夹