首页 > Web开发 > 详细

CSS样式表优先级

时间:2014-03-25 18:01:32      阅读:577      评论:0      收藏:0      [点我收藏+]

使用CSS样式表一共有2种方式:内部和外部,其中内部分为行内样式和嵌入式,外部分为导入式和链接式。

如果需要在不同的方式中设定同一个属性的时候,样式的优先级别就出现了。

测试代码如下:

red.css:

  1. p{
  2. color:red;
  3. }

test.html:

 

<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
<title>Test Document</title>
<style type="text/css">
p{
color:blue;
}
@import url(red.css);
</style>
</head>
<body>
<p style="color:gray;">文字颜色</p>
</body>

此时,显示文字颜色为灰色,说明行内样式优先级别最高:

bubuko.com,布布扣

去掉行内样式之后,显示为蓝色,说明页面嵌入式样式的优先级是仅次于行内样式的:

bubuko.com,布布扣

以上说明页面内部样式的优先级别是高于外部样式的。使用外部样式又有两种方式,分为导入式和链接式。

增加一个样式表:green.css

  1. p{
  2. color:green;
  3. }

分以下两种情况:

情况A:

<link href="green.css" type="text/css" rel="stylesheet">

<style type="text/css">

@import url(red.css);

</style>

情况B:

<style type="text/css">

@import url(red.css);

</style>

<link href="green.css" type="text/css" rel="stylesheet">

经过尝试后发现,外部样式以最后的样式为准。

经过上述测试,可以总结如下:

  • 行内样式 > 嵌入样式 > 外部样式
  • 外部样式中,出现在后面的样式优先级高于出现在前面的。

但是,是不是所有的情况都是如此呢?

将head中的样式代码改为下面的代码:

<style type="text/css">

p{

color:blue;

}

</style>

<style type="text/css">

@import url(red.css);

</style>

此时显示的字体颜色为红色:

bubuko.com,布布扣

再例如:

<style type="text/css">

p{

color:blue;

}

</style>

<link href="green.css" type="text/css" rel="stylesheet">

<style type="text/css">

@import url(red.css);

</style>

此时显示字体颜色还是为红色,此时的优先级为:导入样式 > 链接样式 > 嵌入样式。因此,如果是<head>中存在多个<style>标记,那么这些样式的先后顺序决定了优先级别,而同一 个<style>内部,才会遵循嵌入样式优先于导入样式的规则。

虽然各种使用方法有不同的优先级,但是在写样式的时候,最好只采用1~2种方式,这样利于后期的维护和管理,也不会出现样式冲突的情况。

CSS样式表优先级,布布扣,bubuko.com

CSS样式表优先级

原文:http://www.cnblogs.com/liweitao/p/3623129.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!