【11】css 基本功:引入方式及选择器相关
- 2020 年 1 月 14 日
- 笔记
vue 组件开发,必须熟悉基本的 css 知识及技巧。
目录 1、原生 css 的三种引用方式 2、组件开发中的选择器 2.1、深度作用选择器 2.2、不使用类型选择器 3、css 选择器
1、原生 css 的三种引用方式
内联
将 css 样式代码直接嵌入在style属性中。
<p style='color:red;'>文字颜色为红色</p>
嵌入
将style代码块嵌入在head或body内。
<head> <style type='text/css'> span{ font-size:18px; color: red; } </style> </head>
外部
将css样式定义在单独的css文件中,然后使用link标签在页面内引入。
<link rel="stylesheet" href="common.css" type="text/css">
这是原生的方式。在工程化组件开发中,样式有另外的规则和技巧。
2、组件开发中的选择器
2.1、深度作用选择器
在启用了scoped的样式内,可以使用>>>跨越选择更深的子孙组件。
例如:
<style scoped> .a >>> .b { /* ... */ } </style>
会编译成:
.a[data-v-f3f3eg9] .b { /* ... */ }
有些像 Sass 之类的预处理器无法正确解析 >>>。这种情况下可用 /deep/ 或 ::v-deep 操作符取而代之。
2.2、不使用类型选择器
当在元素选择器在scoped style样式块之内时,例如:
p { color: red }
执行效率会慢很多倍。如果使用 类选择器 或者 id选择器 取而代之,比如:
.example { color: red }
性能影响就会消除。
3、css 选择器
1、元素选择器
p{ color: #00CCFF; }
2、id选择器
#red { color:red; } <li id="red">香蕉</li>
3、类选择器
应用最多的一类选择器。
.fo{ color: #00AA88; } <ul class="fo"> </ul>
4、元素+类选择器
p.important {color:red;} <p class="important"> 这个字体颜色为红色</p>
5、多个类选择器
.important {font-weight:bold;} .warning {font-style:italic;} .important.warning {background:silver;} <p class="important warning"> 该字体显示为加粗、斜体以及背景色为银色的效果 </p>
显示为所有类的样式效果。
6、属性选择器
h2[title] { color:red; } <h2 title="Hello world">Hello world</h2>
为拥有指定属性的元素设置样式。scoped css 模块化即是通过添加随机属性名称实现的。
还可以精准查找属性与属性值:
p[class="important warning"] {color:red} <p class="important warning">字体颜色为红色</p>
须同时满足条件,具有class属性,且属性值为xx。
7、后代选择器
依据元素的上下文位置关系确定:
li strong { font-style: italic; font-weight: normal; } <li><strong>苹果</strong></li>
strong在li之后,strong为li的后代。
8、子元素选择器
h1 > strong {color:red;} <h1>This is <strong>very</strong> <strong>very</strong> important.</h1>
两个very均为红色。该选择器选择作为子元素的元素。
9、兄弟选择器
选择相邻的另一元素,二者有相同父元素。
h1 + p {margin-top:50px;} <h1>This is a heading.</h1> <p>和h1有距离</p> <p>This is paragraph.</p>
效果:
紧随的第一个p有样式效果。
10、:last-child 选择器
指定属于其父元素的最后一个子元素的样式。
p:last-child{ background:#ff0000; }
p:last-child 等同于 p:nth-last-child(1)。
11、:first-child 选择器
指定属于其父元素的首个子元素的样式。
p:first-child{ background-color:yellow; }
例如:
p:first-child i { background:yellow; }
选择每个 <p>
中的每个 <i>
元素并设置其样式,其中的 <p>
元素是其父元素的第一个子元素。
参考链接
- https://cloud.tencent.com/developer/article/1514516
- https://vue-loader.vuejs.org/zh/guide/scoped-css.html
- https://www.jianshu.com/p/e56f07f8da62
- http://w3school.com.cn/cssref/selector_last-child.asp
专栏列表
基于 vue+go 如何快速进行业务迭代?