apacheao / blog

0 stars 0 forks source link

你不知道的Pseudo #15

Open apacheao opened 4 years ago

apacheao commented 4 years ago

Pseudo分 Pseudo classPseudo element

Pseudo class: 常见的五大伪类,也是浏览器最早实现的五大伪类,都针对于链接/行为

  1. :any-link (选中带link的a标签) example
  2. :link :visited (表示 already visited this link) example
  3. :hover (hovering over this link) example
  4. :active (This link will turn while you click on it.) example
  5. :focus [when the user clicks or taps on an element or selects it with the keyboard's "tab" key.] example
  6. :target [常用于锚点跳转,:target表示跳转到当前的元素] example

还有一类为选择类似于选择元素在父元素的索引 :last-child :last-of-type :not() :nth-child() :nth-last-child() :nth-last-of-type() :nth-of-type() :only-child :only-of-type 这些伪类我们因减少使用,因为其中的一部分会造成回溯 对css computed消耗较大。其伪类的语法和功能我们可以去MDN查询

apacheao commented 4 years ago

Pseudo element: 常见的四大伪元素,也是兼容性达到可用的四个

  1. ::first-line [表示元素的第一行]
  2. ::first-letter [元素的第一个字母]
  3. ::before
  4. ::after
apacheao commented 4 years ago

::first-line 元素中不是纯文本,规则就变得复杂了 举个栗子:

<div>
  <p id=a>First paragraph</p>
  <p>Second paragraph</p>
</div>

div>p#a {
    color:green;
}

div::first-line { 
    color:blue; 
}

这段代码最终结果第一行是蓝色,因为 p 是块级元素,所以伪元素出现在块级元素之内,所以内层的 color 覆盖了外层的 color 属性。

如果我们把 p 换成 span,结果就是相反的。

<div>
  <span id=a>First paragraph</span><br/>
  <span>Second paragraph</span>
</div>

div>span#a {
    color:green;
}

div::first-line { 
    color:blue; 
}

这段代码的最终结果是绿色,这说明伪元素在 span 之外

CSS 标准只要求 ::first-line 和 ::first-letter 实现有限的几个 CSS 属性,都是文本相关,这些属性是下面这些。

apacheao commented 4 years ago

::before [creates a pseudo-element that is the first child of the selected element. It is often used to add cosmetic content to an element with the content property.] example

::after [creates a pseudo-element that is the last child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.] example