Issue
I am experiencing unexpected behavior with flexbox and the gap
property. To my surprise when I "refresh" the DOM by removing the element and adding it back everything works as expected. This leads me to believe that the first paint bugs out somehow and when I "force reload" it fixes itself.
The issue is with a simple inline-flex
element that contains inline words and an absolutely positioned span between the first two. The gap
is applied between the first two words but I shouldn't be, since they aren't actual block children elements. Without the span the gap is not created.
The GIF below shows the strange behavior best. What is going on here and is there any way to fix it?
HTML
<div>
Left <span class="show-for-sr">sr label </span>Right with SR label
</div>
<br>
<div>
Left Right without SR label
</div>
CSS
.show-for-sr {
position: absolute !important;
width: 1px !important;
height: 1px !important;
padding: 0 !important;
overflow: hidden !important;
clip: rect(0, 0, 0, 0) !important;
white-space: nowrap !important;
border: 0 !important;
}
div {
position: relative;
display: inline-flex;
align-items: center;
gap: 3.5em;
}
Solution
The gap is applied between the first two words but I shouldn't be, since they aren't actual block children elements.
The gap should be applied and this is the correct behavior. The use of position: absolute
doesn't matter. The HTML code is what you need to consider.
From the specification:
Each in-flow child of a flex container becomes a flex item, and each contiguous sequence of child text runs is wrapped in an anonymous block container flex item.
So when having:
<div>
Left <span class="show-for-sr">sr label </span>Right with SR label
</div>
It means that you have 2 "contiguous sequence of child text" plus the span element. So 3 flex items in total and if you make the span position: absolute
then only 2 flex items are remaining and you get the result you see.
The Gold Rule of flexbox is to never make a text container a flexbox container: https://dev.to/afif/never-make-your-text-container-a-flexbox-container-m9p
You should wrap the content within another container:
<div>
<span>Left <span class="show-for-sr">sr label </span>Right with SR label</span>
</div>
Answered By - Temani Afif
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.