CSS属性规则在HTML文件中不起作用



请不要太刻薄,我只是想理解。好吧,所以我精通C++、Java和C#应用程序。我最近一直在努力了解网络开发。现在我正在复习基本的HTML编码。正在查看http://www.westciv.com/style_master/academy/css_tutorial/introduction/how_they_work.html并试图重建https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/How_CSS_works.但它并没有按预期发挥作用。

<!DOCTYPE html>
<html>
<head>
	<style type ="text/css">	<!-- You need this in order to have CSS, it has --> 
		p {color: blue; font-family:arial;}
	</style>
</head>
<body>
<h1>Hello World!</h1>
<p>This is my first CSS example</p>
<ul>
<li>This is</li>
<li>a list</li>
</ul>
</body>
</html>

因此,当我在Codepen中键入此代码时,它会按预期工作,每个段落都显示蓝色文本。然而,当我在notepad++中将其编码为HTML文件时,它不会添加CSS样式、格式、背景色等。在查看它时,我发现如果我直接在段落括号中添加样式,它会起作用(如下所示)

<!DOCTYPE html>
<html>
<head>
	    <style type ="text/css">	
		    p {color: blue;}
	    </style>
</head>
<body>
	    <p style="text-decoration: underline;">This is my body green</p>
	    <p style = "color: blue;">this text should be blue!</p>
<h1>Hello World!</h1>
<p>This is my first CSS example</p>
<ul>
<li>This is</li>
<li>a list</li>
</ul>
</body>
</html>

添加像<meta charset="utf-8><link rel="stylesheet" href="style.css">这样的解密块也没有帮助。

我的问题是,为什么这个代码在某些地方有效,而在其他地方无效?是否存在可能会造成干扰的网络浏览器设置?我尝试过IE、FF和Chrome,但它们都不会显示CSS样式,除非我在括号中而不是在标题中明确声明它。如果这是一个逻辑错误,请发表/评论文章阅读。

在第一个示例中,注释<!-- You need this in order to have CSS, it has -->被放错了CSS声明的位置,所以不要将HTML注释放在CSS声明中。

声明p {color: blue; font-family:arial;}只影响到<P></P>标记。

<!DOCTYPE html>
<html>
<head>
	<style type ="text/css">	
		p {color: blue; font-family:arial;}
	</style>
</head>
<body>
<h1>Hello World!</h1>
<p>This is my first CSS example</p>
<ul>
<li>This is</li>
<li>a list</li>
</ul>
</body>
</html>

如果需要为特定标记添加特定格式,可以使用class属性(class="blue"),并在CSS中声明一个类,在类名(.blue)的开头添加一个点。

<!DOCTYPE html>
<html>
<head>
	    <style type ="text/css">	
p {color: blue;}
.underlined { text-decoration: underline }
.blue {  color: blue }
	    </style>
</head>
<body>
	    <p class="underlined">This is my body green</p>
	    <p class="blue" >this text should be blue!</p>
<h1>Hello World!</h1>
<p>This is my first CSS example</p>
<ul>
<li>This is</li>
<li>a list</li>
</ul>
</body>
</html>

您不需要声明样式类型,因为唯一的类型是CSS。

<!DOCTYPE html>
<html>
<head>
	<style>
		p {color: blue; font-family:arial;}
	</style>
</head>
<body>
<h1>Hello World!</h1>
<p>This is my first CSS example</p>
<ul>
<li>This is</li>
<li>a list</li>
</ul>
</body>
</html>

最新更新