如何在父元素的上方(和旁边)放置一个:: before伪元素,而不影响父元素的位置

问题描述 投票:3回答:2

我有一个包含fieldsetlegend,它有一个::before伪元素,我希望这个伪元素位于legend上方而不影响legend的位置。

HTML:

<fieldset>
    <legend>THE TEXT</legend>
</fieldset>

CSS:

legend {
    padding:0 14px;
}

legend::before {
    content:'BEFORE ';
    color:red;
}

JSFiddle demo

我尝试添加legend::before { vertical-align:super },但它将legend元素放下来像这样:

JSFiddle demo superscript (without success)

任何想法都欢迎这样做。

html css pseudo-element
2个回答
6
投票

像这样在伪元素上使用position: absolute;

legend {
    padding:0 14px;
    position: relative;
}

legend:before {
    content:'BEFORE';
    color:red;
    position: absolute;
    top: -20px;
}

看到这个jsFiddle

编辑:

如果您希望文本显示在图例旁边,请使用left属性。

查看更新的jsFiddle


0
投票

我刚刚为自己的问题找到了一个解决方案,将display:block;float:left添加到::before使它按我的意愿工作。然后,我可以在不影响图例的情况下为元素添加边距:

传奇{padding:0 14px; }

legend::before {
    content:'BEFORE';
    color:red;
    float:left;
    margin-top:-5px;
    padding-right:5px;
}

JSFiddle demo

© www.soinside.com 2019 - 2024. All rights reserved.