我是一个完整的 html/css 初学者。
我使用 PHP 在不同的网页中包含相同的头部部分。 head 部分中有一个链接到外部 css 的 href 链接。用于设置多个网页布局样式的文件。
由于不同的网页位于根文件夹中的不同子文件夹中,因此我必须使用绝对路径来链接css。文件,问题来了:我不知道如何正确编写它。
当我为每个单独的网页使用相对路径时,链接工作正常,但是当我尝试使用绝对路径时,它根本不起作用。
我试过了:
1.href="file:///C:\xampp\htdocs\root\styles\style.css"
2.href="file:///C:/xampp/htdocs/root/styles/style.css"
3.href="file://C:/xampp/htdocs/root/styles/style.css"
4.href="C:/xampp/htdocs/root/styles/style.css"
5.href="c:/xampp/htdocs/root/styles/style.css"
这是代码的开头部分:
<!DOCTYPE html>
<html lang="en">
<head>
<?php include('common/head.php') ?>
<title>Home</title>
</head>
这是头部部分:
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="file:///C:\xampp\htdocs\root\styles\style.css">
最佳答案
我想这是服务器端和客户端执行上下文之间的普遍误解。
http://localhost/whatever/index.htm
的 html 文档 href="styles/style.css"
相对路径。浏览器将在 http://localhost/whatever/styles/style.css
href="/styles/style.css"
一种绝对路径。浏览器将请求服务器 url 根目录下的文件 http://localhost/styles/style.css
href="http://localhost/foobar/styles/style.css"
绝对路径。浏览器将尝试从那里准确下载。 href="file:///C:\...."
系统上的本地路径。服务器与它无关。该页面可能只能在您自己的系统上运行,而不能在其他人从其他计算机通过服务器访问它时运行。 你的浏览器应该自带一些开发工具。您可以检查浏览器正在请求什么以及您的服务器使用该工具响应什么。
答案是:在此处使用相对或某种绝对网址。
关于html - css文件链接到html时如何正确写出本地文件的绝对路径?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58432164/