gpt4 book ai didi

css - 没有绝对定位的伪元素

转载 作者:行者123 更新时间:2023-11-28 12:09:16 25 4
gpt4 key购买 nike

我想将一个 CSS 伪元素垂直定位到它所附加的 div 元素的顶部。这是代码:

html

<div class="container">
<div class="content">
text
</div>
</div>

CSS

.container {
padding: 20px;
}

.content {
padding: 10px;
}

.content::after {
content: '';
background: red;
width: 10px;
height: 10px;
float: right;
}

注意事项是我不能在伪元素上使用 position: absolute 或负边距。内容 div 被动态插入到使用 flex-box 的容器 div 中,因此绝对位置不起作用。内容 div 的高度也不同,因此不能使用负边距顶部。

这是 fiddle .

最佳答案

通过 float ,并使用伪 :before 代替,您将其从文本之前的流程中取出,并结合 transform: translate,您可以实现这一点。

.container {
padding: 20px;
background-color: #ddd;
}

.content {
width: 50%;
background: white;
padding: 20px;
}

.content:before {
content: '';
background: red;
width: 10px;
height: 10px;
float: right; /* out of flow, position right of text */
transform: translateY(-20px); /* match padding value */
}
<div class="container">
<div class="content">
text text text<br>
</div>
</div>

<div class="container">
<div class="content">
text text text<br>
text text text<br>
text text text<br>
text text text<br>
text text text<br>
text text text<br>
text text text<br>
</div>
</div>

已更新

我还要说的是display: flex也不会有问题,无论是在container,content上设置或两者兼而有之。

Flex 子元素在设置时尊重定位,如果 display: flex 仅在 container 上设置,伪元素甚至不是 flex 元素。

如果需要,您还可以使用 after 伪,因为在某些情况下,如果需要使用 nth-* 或类似的,使用哪个效果最好可能会更容易。

.container {
display: flex;
padding: 20px;
background-color: #ddd;
}

.container > * {
position: relative; /* give first child position */
}

.content {
width: 50%;
background: white;
padding: 20px;
}

.content:before {
content: '';
position: absolute; /* absolute position */
background: red;
width: 10px;
height: 10px;
right: 20px; /* match padding value */
top: 0;
}
<div class="container">
<div class="content">
text text text<br>
</div>
</div>

<div class="container">
<div class="content">
text text text<br>
text text text<br>
text text text<br>
text text text<br>
text text text<br>
text text text<br>
text text text<br>
</div>
</div>

关于css - 没有绝对定位的伪元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35241772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com