定義
:before 選擇器在被選元素的內(nèi)容前面插入內(nèi)容。
解析
定義中提到,是在被選元素的 內(nèi)容 前面插入內(nèi)容,如下圖,div 是一個容器,div 中的內(nèi)容是 testDiv元素
,css 中的 :before
和 after
都顯示在 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>