Search code examples
htmlcssflexboxdisplayword-wrap

How to format HTML text so it wraps around keywords


So I have this code with a paragraph with keywords and text.

I need to make the format so that the keywords appear next to other, the text starts where the keywords end and then the text also wraps around the keywords.

I tried doing it with display: flex but I just couldn't figure out the way to get the desired outcome. Also the text on the line after the first one should have a small margin to the left, aka to not be in line with the start of the keywords.

I am here putting my code, an also a screenshot of how the desired outcome should be.

Any help is appreciated. Thank you.

.paragraph {
  display: flex;
  width: 320px;
}

.keywords {
  display: flex;
}

.keywords .item {
  font-family: "Times New Roman", Times, serif;
  color: #000;
  font-style: italic;
  white-space: nowrap;
}

.keywords .item::after {
  content: "-";
  margin-left: 5px;
  margin-right: 5px;
  font-family: "Times New Roman", Times, serif;
  font-weight: 500;
}

.text {
  font-family: "Times New Roman", Times, serif;
  color: #000;
  font-style: italic;
  font-weight: 300;
}
<div class="paragraph">
  <div class="keywords">
    <div class="item">KEYWORD 1</div>
    <div class="item">KEYWORD 2</div>
  </div>
  <div class="text">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
</div>

The correct format should look like this:

Correct format


Solution

  • Wrapping text around an element pretty much requires the use of float.

    For this reason the "paragraph" wrapper cannot be display: flex as this negates the use of float. Here I have used inline-block instead.

    .paragraph {
      display: inline-block;
      width: 320px;
    }
    
    .keywords {
      display: flex;
      float: left;
    }
    
    .keywords .item {
      font-family: "Times New Roman", Times, serif;
      color: #000;
      font-style: italic;
      white-space: nowrap;
    }
    
    .keywords .item::after {
      content: "-";
      margin-left: 5px;
      margin-right: 5px;
      font-family: "Times New Roman", Times, serif;
      font-weight: 500;
    }
    
    .text {
      font-family: "Times New Roman", Times, serif;
      color: #000;
      font-style: italic;
      font-weight: 300;
      margin-left: 1em;
    }
    <div class="paragraph">
      <div class="keywords">
        <div class="item">KEYWORD 1</div>
        <div class="item">KEYWORD 2</div>
      </div>
      <div class="text">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
    </div>