Home > database >  Force a div to the end of a text node
Force a div to the end of a text node

Time:09-13

We have html that is generated by a third-party which is periodically updated so a javascript solution won't do.

Here is an example of the generated html:

<div >
  <div >*</div>
  I am a text node
</div>

Which (without css) renders like:

no style render

I'm trying to align the asterisk to the end of the text node which I've achieved with the below css...

.label {
  display: flex;
  flex-direction: row-reverse;
  justify-content: flex-end;
}

Result:

current css render

However, the problem occurs when the text node wraps onto the next line...

wrapping issue

Desired result...

desired result


Update

Adding align-items: flex-end; is a closer result!

enter image description here


Update 2

From @OMi Shah's comment adding flex-wrap: wrap-reverse; is close but not quite there...

enter image description here

CodePudding user response:

Add a align-self to the .asteriks

.label {
  display: flex;
  flex-direction: row-reverse;
  justify-content: flex-end;
  
  margin-bottom: 2em; /* only for demo */
}
.asterisk { align-self: flex-end }
<div >
  <div >*</div>
  I am a text node
</div>

<div >
  <div >*</div>
  I am a <br />
  text node
</div>

<div >
  <div >*</div>
  I am<br />
  a <br />
  text <br />
  node
</div>

CodePudding user response:

For those browsers that support CSS :has (which is Chrome/Edge/Safari but Firefox requires a setting) this snippet seems to work:

Abandon ideas of trying to get that asterisk in the div into the right place and instead get rid of it and set the asterisk in an after pseudo element.

This snippet has a large font size so it's easier to test the width getting smaller:

div.label {
  font-size: 76px;
}

div.label:has(.asterisk)::after {
  content: '*';
}

div.label div.asterisk {
  display: none;
}
<div >
  <div >*</div>
  I am a text node
</div>

  • Related