我想使用css属性:: before在段落之前添加标签。 我设法正确呈现标记,但是它将段落中的文本推到右侧。我想避免这种情况,因为标签将放置在段落的左上角,并且文本应位于标签下。
我看着w3schools试图找出它是如何完成的。
我还尝试查看我看到该设计的网站,但不知道它是如何工作的。这是网站链接:Fetch API
我尝试做的事情是在该网站上的第2.1节“ URL”下完成的。
.note {
background-color: #C7FDBC;
padding: 0.6em;
margin-left:1em;
margin-top: 2em;
margin-bottom: 1.5em;
}
.note::before {
content: "Note";
background-color: green;
color: white;
font-weight: bold;
padding: 0.4em;
position: relative;
top: -1.6em;
left: -1.3em;
}
<p class="note">The note</p>
预期结果类似于获取API中的注释。 我的结果看起来很相似,只是段落文本被向右推了与:: before内容的宽度相同的量。
答案 0 :(得分:2)
如果您不希望您的::before
伪元素影响其他元素的流程,请给它position: absolute
。为了相对于<p>
进行绝对定位,您必须给<p>
除static
以外的位置:在这里我将使用relative
。
之所以可行,是因为::before
伪元素被视为您的<p>
的子元素:
body
{
padding: 1em;
}
.note {
background-color: #C7FDBC;
padding: 0.6em;
margin-top: 2em;
margin-bottom: 1.5em;
position: relative;
}
.note::before {
content: "Note";
background-color: green;
color: white;
font-weight: bold;
padding: 0.2em;
position: absolute;
top: -1.4em;
left: -1.1em;
}
<p>This is text before the note. See how the left edge of this text is aligned with the left edge of the note?</p>
<p class="note">This is the note.</p>
<p>This is text after the note. See how the left edge of this text is aligned with the left edge of the note?</p>
注意:(看看我在那儿做了什么?)
由于此方法可以防止覆盖层影响元素的布局,因此除非对其进行填充,否则覆盖层将被页面边缘剪裁(这就是为什么我向{{1}添加一些padding
}。
答案 1 :(得分:1)
arrayMenu = ["'A'","'B'","'C'"]
伪元素在功能上是其应用到的任何元素的子元素。就您而言,这类似于::before
解决方案是使用<p class="note"><::before>Note</::before>The note</p>
将.note
建立为定位上下文,然后使用position: relative
将position: absolute
定位在所需的伪位置。