将一个伪元素直接放置在另一个伪元素之上的最佳方式是什么?
假设我想在此处的标签旁边显示一个奇特的“复选框”:
label:before {
content: "\00a0";
color: #FFF;
height: 6px;
width: 6px;
display: inline-block;
}
label:after {
content: "\00a0";
height: 18px;
width: 18px;
display: inline-block;
background: #ebd196;
background-image: linear-gradient(top, #ebd196 4%, #e2b65d 5%, #ab8844 100%);
}
<input id="pretty"><label for="pretty">Label text</label>
伪元素的堆叠顺序是什么? :before 出现在 :after- 的下方还是上方,哪个更适合作为边框,哪个更适合填充?
什么是应用于标签的最佳定位,label:before & label:after 以获得正确的定位?
最佳答案
:before
(或 ::before
)被视为应用它的元素的第一个子元素,而 :after
(或 ::after
)被视为最后一个 child 。因此,:after
自然会覆盖:before
。
https://developer.mozilla.org/en-US/docs/Web/CSS/::before
https://developer.mozilla.org/en-US/docs/Web/CSS/::after
我认为确保它们对齐的最佳方法是在 label
和 position: absolute;
上使用 position: relative;
在伪元素上以及 top
、bottom
等的相同值
如果你想使用伪元素制作渐变边框,那么你可以这样做:
label {
position: relative;
display: inline-block;
padding: 0 2px;
margin: 2px;
}
label:before {
content:"";
position: absolute;
top: 0;
left: 0;
z-index: -1;
width: 100%;
height: 100%;
background: white;
}
label:after {
content:"";
position: absolute;
top: -2px;
bottom: -2px;
left: -2px;
right: -2px;
z-index: -2;
background: linear-gradient(to bottom, #1e5799 13%, #efe22f 79%);
}
您可能会发现这很有用:
关于html - 如何定位:before & :after pseudo-elements on top of each other?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19415641/