HTML style 属性包含一个 CSS 样式声明,用于将其应用于元素。
这是一个全局属性,建议在单独的文件中定义样式。style 属性和 <style> 元素具有相同的用途,即允许快速设置样式。
如果 style 属性用于任何元素的样式设置,则可以将其称为内联 CSS。
语法
<element style="property:value;">
适用对象
由于 style 属性是全局属性,因此它适用于所有元素,尽管它可能对某些元素(放置在头部元素内的标签)没有影响。
HTML style 属性示例
下面的示例将说明 HTML style 属性,我们应该在哪里以及如何使用此属性!
使用 style 属性的内联样式
在下面的示例中,我们创建了两个元素 h1 和 p,并在它们上应用了style 属性。
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML style attribute</title>
</head>
<body>
<!-- Example of style attribute-->
<h1>
<span style="color: green;">Qikepu</span>.com
</h1>
<p style="margin-top: -20px; margin-left: 100px">
Simply Easy Learning
</p>
</body>
</html>
使用 style 属性覆盖内部 CSS
内部 css 是最优先的 css,如果我们在任何元素上应用 CSS 并在该元素上使用 style 属性来更改样式,它将优先考虑内联 css。
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML style attribute</title>
<style>
span{
color: black;
}
</style>
</head>
<body>
<!-- Example of style attribute-->
<h1>
<span style="color: green;">Qikepu</span>.com
</h1>
<p style="margin-top: -20px; margin-left: 100px">
Simply Easy Learning
</p>
</body>
</html>
覆盖样式属性值
正如您在前面的示例中看到的,内联 CSS 是浏览器遵循的最优先的 CSS。但是,如果我们使用 !important as,那么我们可以覆盖样式属性值。color: black !important;
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML style attribute</title>
<style>
span{
color: black !important;
}
</style>
</head>
<body>
<!-- Example of style attribute-->
<h1>
<span style="color: green;">Qikepu</span>com
</h1>
<p style="margin-top: -20px; margin-left: 100px">
Simply Easy Learning
</p>
</body>
</html>
支持的浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
是否支持 | Yes | Yes | Yes | Yes | Yes |