Reputation: 685
I'm having trouble aligning an ::before
CSS pseudo-element with the selected element. Both the selected element and the pseudo-element are text. Sometimes it will align, but if the browser breaks the selected element, it will not align correctly. Bellow is my code:
p {
width: 300px;
line-height: 5em;
}
span {
border-bottom: solid 16px;
}
span::before {
position: absolute;
content: attr(data-label);
font-size: 14px;
}
.level-1 {
padding-bottom: 0px;
}
.level-2 {
padding-bottom: 16px;
}
.level-3 {
padding-bottom: 32px;
}
.level-1::before {
margin-top: 16px;
}
.level-2::before {
margin-top: 32px;
}
.level-3::before {
margin-top: 48px;
}
span[data-uid="001"] { border-color: #F9CC88; }
span[data-uid="002"] { border-color: #FEB396; }
span[data-uid="003"] { border-color: #AED4D5; }
<p>
Lorem <span class="level-1" data-uid="003" data-label="Level1">ipsum dolor <span class="level-2" data-uid="001" data-label="Level2">sit amet, <span class="level-3" data-uid="002" data-label="Level3">consectetuer adipiscing</span> elit.</span></span>
</p>
Expected:
Actual:
Why does this happen and how to solve it?
Upvotes: 0
Views: 93
Reputation: 36567
A way round it, but rather hacky, is to make the pseudo elements after rather than before. This seems to jog the browser into realising it shouldn't overflow the text but start on the next line like its owning element.
Also, make the pseudo element position relative to its span by setting position of the spans and adjusting the resulting vertical alignment.
(Note: I added a little more text so the problem shows).
p {
width: 300px;
line-height: 5em;
}
span {
border-bottom: solid 16px;
}
span::after {
position: absolute;
content: attr(data-label);
font-size: 14px;
left: 0;
top: -32px;
}
.level-1 {
padding-bottom: 0px;
}
.level-2 {
padding-bottom: 16px;
}
.level-3 {
padding-bottom: 32px;
}
.level-1::after {
margin-top: 16px;
}
.level-2::after {
margin-top: 32px;
}
.level-3::after {
margin-top: 48px;
}
span[data-uid="001"] {
border-color: #F9CC88;
}
span[data-uid="002"] {
border-color: #FEB396;
}
span[data-uid="003"] {
border-color: #AED4D5;
}
span {
position: relative;
}
<p>
Lorem <span class="level-1" data-uid="003" data-label="Level1">ipsum dolor <span class="level-2" data-uid="001" data-label="Level2">sit amet, more text <span class="level-3" data-uid="002" data-label="Level3">consectetuer adipiscing</span> elit.</span>
</span>
</p>
Tested on Windows10 (Edge/Chrome and Firefox) and IOS 14.7.1 (Safari)
Upvotes: 1