关于外部样式表中background-image:url()的设置

在前文中曾经提到,我遇到了一个问题,就是在外部CSS文件中定义了背景图,无法在引用它的html文件中显示。具体来说是这样的:样式表文件Style1.css放在~/Style文件夹下,在~/Admin文件夹下有个index.aspx引用了这个外部样式表,在Style1.css文件有这样的定义:.logo{background-image:url(../pic/logo.jpg);width:900px; height:100px; text-align:center;margin-left:auto;margin-right:auto;},但是,index.aspx并无法显示指定的背景图片,而其它样式都没有问题。今天抽时间琢磨了一下,终于弄明白是啥原因啦。

原来,这个错误源于我对外部CSS文件的一个误解。我一直以为,当在html中引用外部样式表后,那么在样式表文件中定义的样式就相当于在html头文件中定义的样式了。但事实证明并非如此,它依然存放在定义的文件中被一起下载到客户端。这一点从background-image的url属性定义的实践上也可以清楚地看出,在定义url时,如果是绝对地址当然没什么问题,如果是相对地址,那么,一定要相对style1.css所在的路径,而不必考虑即将引用它的html文件的路径。

现在想明白这个事儿,再回过头来看看,其实人家这个设计也是顺其自然的设计。试想,如果以引用者的文件路径为准,那该给使用者造成多大的麻烦啊——瞧我这浆糊脑袋!

最后总结一下:在外部样式表中定义url属性时,如果采用相对路径,那么这个路径一定是以该样式表文件所在路径为准的。经验之谈,有失偏颇之处欢迎指正。

请把一下代码每一行的用途注释上:<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>登录表单</title> <style> body { background-image: url("background.jpg"); background-size: cover; font-family: "宋体"; font-size: 30px; } form { margin: auto; width: 50%; background-color: rgba(255,255,255,0.8); padding: 20px; border-radius: 10px; } input[type=text], input[type=password] { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } input[type=submit], input[type=reset] { background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px 0; border: none; border-radius: 4px; cursor: pointer; } input[type=submit]:hover, input[type=reset]:hover { background-color: #45a049; } .error { color: red; } </style> </head> <body> <form> <h2>登录</h2> <label for="username">用户名</label> <input type="text" id="username" name="username" ><br> <label for="password">密码</label> <input type="password" id="password" name="password" ><br> <label for="confirm_password">确认密码</label> <input type="password" id="confirm_password" name="confirm_password" ><br> <input type="submit" value="登录"> <input type="reset" value="重置"> <span class="error" id="password_error"></span><br> <a href="https://www.baidu.com/">忘记密码?</a> </form> <script> document.querySelector("form").addEventListener("submit", function(event) { var password = document.querySelector("#password").value; var confirm_password = document.querySelector("#confirm_password").value; if (password != confirm_password) { document.querySelector("#password_error").innerHTML = "密码不一致"; event.preventDefault(); } }); </script> </body> </html>
05-24
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极客行天下

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值