CSS 中的 :before 和 :after 的一點(diǎn)小知識點(diǎn)

定義

:before 選擇器在被選元素的內(nèi)容前面插入內(nèi)容。

解析

定義中提到,是在被選元素的 內(nèi)容 前面插入內(nèi)容,如下圖,div 是一個容器,div 中的內(nèi)容是 testDiv元素,css 中的 :beforeafter 都顯示在 div 內(nèi)部,二者分別位于 testDiv元素 內(nèi)容的前后。

偽元素
<template>
  <div class="test-wrapper">
    <div class="test-div">testDiv元素</div>
  </div>
</template>

<script>
export default {}
</script>

<style lang="scss" scoped>
.test-wrapper {
  padding: 20px;
  position: relative;
  background-color: #fff;
}
.test-div {
  width: 500px;
  height: 50px;
  background-color: pink;
  padding: 5px;
  position: relative;
}
.test-div::before {
  content: '12';
  background-color: yellow;
}
.test-div::after {
  content: 'after元素';
  background-color: yellowgreen;
}
</style>

所以可以看到,偽元素也是被選元素的內(nèi)容,只是會插入到被選元素原本內(nèi)容的前后。

偽元素的 display 屬性

插入的偽元素默認(rèn)是 display 屬性,如果想要為偽元素設(shè)置寬高等,需要修改偽元素的 display 屬性為 inline-block 或者 block。

偽元素的定位

偽元素插入的位置是被選元素的 內(nèi)容 的前或者后,因此本質(zhì)上偽元素也是被選元素的子元素。所以定位時,被選元素就是偽元素的父元素。
如圖,被選元素 test-div 設(shè)置了 position: relative,外部元素 test-wrapper 也設(shè)置了 position: relative,然后對被選元素的偽元素 :after 設(shè)置定位,可以看到,偽元素的位置是根據(jù) test-div 來定位的,因此,可以驗(yàn)證 被選元素就是偽元素的父元素 這句話。

偽元素的定位
<template>
  <div class="test-wrapper">
    <div class="test-div">testDiv元素</div>
  </div>
</template>

<script>
export default {}
</script>

<style lang="scss" scoped>
.test-wrapper {
  padding: 20px;
  position: relative;
  background-color: #fff;
}
.test-div {
  width: 500px;
  height: 50px;
  background-color: pink;
  padding: 5px;
  position: relative;
}
.test-div::before {
  content: '12';
  background-color: yellow;
  width: 100px;
  height: 30px;
  display: inline-block;
}
.test-div::after {
  content: 'after元素';
  background-color: yellowgreen;
  width: 80px;
  height: 20px;
  display: block;
  position: absolute;
  left: 0;
}
</style>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。