今天写java时遇到一个问题,给网页body编写css样式时background-image显示无效。上网查了才知道是路径有问题。
开始搞不懂为什么img标签就可以。现在记录下来方法方便以后忘记后查阅。
1.ccs样式background-image url() 失效原因。
我想在index.jsp中用background-image 引入upload下的mapleLeaf.jpg.例如这样:
<body style="background-image: url(/upload/mapleLeaf.jpg)">效果是不显示的。
2.解决办法:用相对路径。所谓相对路径,就是相对于自己的目标文件位置。 上图我是想在index.jsp文件里面引入upload下的mapleLeaf.jpg图片,那么mapleLeaf.jpg相对于index.jsp来说是在其所在目录upload的子目录里面。引用的图片语句应该为:
<body style="background-image: url(./upload/mapleLeaf.jpg)">
这里要注意"./" ,"../","/" 他们之间的区别。
"./": 表示当前目录
"../": 表示父级目录
"/" : 表示根目录
3.下面总结一下相对路径的写法:(抄的百度)
相对路径就是指由这个文件所在的路径引起的跟其它文件(或文件夹)的路径关系。
1 两个文件在同一个文件夹下,直接写文件名即可
假设info.html路径是:c:\Inetpub\wwwroot\sites\blabla\info.html
假设index.html路径是:c:\Inetpub\wwwroot\sites\blabla\index.html
在info.html加入index.html超链接的href应该这样写:index.html
2 要引用的文件在下一级文件夹下,文件名前加子文件夹名称
假设info.html路径是:c:\Inetpub\wwwroot\sites\blabla\info.html
假设index.html路径是:c:\Inetpub\wwwroot\sites\blabla\html\tutorials\index.html
在info.html加入index.html超链接的href应该这样写:html/tutorials/index.html
3 要引用的文件在上一级文件夹下,文件名前加../
假设info.html路径是:c:\Inetpub\wwwroot\sites\blabla\info.html
假设index.html路径是:c:\Inetpub\wwwroot\sites\index.html
在info.html加入index.html超链接的代码应该这样写:<a href="../index.html">index.html</a>
举一反三: ../表示源文件所在目录的上一级目录,../../表示源文件所在目录的上上级目录,以此类推。
4 更复杂的情况:
假设info.html路径是:c:\Inetpub\wwwroot\sites\blabla\info.html
假设index.html路径是:c:\Inetpub\wwwroot\sites\html\index.html
在info.html加入index.html超链接的代码应该这样写:<a href="../html/index.html">index.html</a>