简体   繁体   English

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

[英]How to put a ::before pseudo-element above (and next to) the parent element without affecting the parent's position

I have a fieldset containing a legend that has a ::before pseudo-element and I want this pseudo-element to be positioned above the legend without affecting the legend 's position. 我有一个包含一个带有::before伪元素的legendfieldset ,我希望这个伪元素位于legend上方,而不会影响legend的位置。

HTML: HTML:

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

CSS: CSS:

legend {
    padding:0 14px;
}

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

JSFiddle demo JSFiddle演示

I tried adding legend::before { vertical-align:super } but it puts the legend element down like this: 我尝试legend::before { vertical-align:super }添加legend::before { vertical-align:super }但它将legend元素放下来像这样:

JSFiddle demo superscript (without success) JSFiddle演示上标(没有成功)

Any idea's would be welcome to accomplish this. 任何想法都欢迎这样做。

Use position: absolute; 使用position: absolute; on the pseudo element like this: 像这样的伪元素:

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

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

See this jsFiddle 看到这个jsFiddle

EDIT: 编辑:

If you would like the text to appear beside the legend then use the left attribute. 如果您希望文本显示在图例旁边,请使用left属性。

See updated jsFiddle 查看更新的jsFiddle

I just found a solution for my own question, adding display:block; 我刚刚为自己的问题找到了解决方案,添加了display:block; and float:left to the ::before makes it works as I want. float:left::before让它按我想要的方式工作。 I could then add margins to the element as I wanted without affecting the legend: 然后,我可以在不影响图例的情况下为元素添加边距:

legend { padding:0 14px; 传奇{padding:0 14px; } }

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

JSFiddle demo JSFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM