HGPB
HGPB

Reputation: 4376

Prevent inline block from wrapping but allow content to wrap

I have this layout:

<ul style="white-space:nowrap;">
    <li style="width:200px; display:inline-block;"></li>
    <li style="display:inline-block; vertical-align:top; padding-left:10px;"></li>
</ul>

I have managed to stop the ul from wrapping which is a start. However, the content in the 2nd li continues off screen. Overlapping its parent elements etc.

I need the 2nd li to take up the slack and be dynamic in width unlike the first li. And I need the text to wrap inside the 2nd li.

Upvotes: 12

Views: 14467

Answers (4)

Timidfriendly
Timidfriendly

Reputation: 3284

li {display:table;}

is your friend. Also, don't forget to remove inline-styles!

Upvotes: 9

vhs
vhs

Reputation: 10079

This is a practical use case for CSS Grid Layout:

ul {
  display: grid;
  grid-template-columns: 200px 1fr;
  column-gap: 10px;
}
li {
  display: unset; /* reset user agent list-style */
}
img {
  background: #00bcd4; /* style image background */
}
<ul>
<li><img width="200" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20/%3E%0A">
<li>long text content next to the image long text content next to the image long text content next to the image long text content next to the image
</ul>

Creates two-column grid with 10px column gap. First grid item has 200px width to match your image and the second wrapping text.

If if content you're trying to wrap may contain long strings such as an absolute URL or scientific/medical terms like pneumonoultramicroscopicsilicovolcanoconiosis add overflow-wrap to the second li using the :last-of-type pseudo-class.

Upvotes: 0

ma11hew28
ma11hew28

Reputation: 126477

Sounds like you might actually want to use a table.

Otherwise, if you know the width of the image, float it left and give the next element a left margin greater than or equal to the width of the image.

For example:

article > img {
  float: left;
  height: 80px;
  width: 80px;
}
article > div {
  margin-left: 90px;
}
<article>
  <img src="http://www.gravatar.com/avatar/7e6e0e2b73358e47e0b7f83f8111f75b">
  <div>
    <h4>Matt Di Pasquale</h3>
    <p>I know the width of the image is 80px, so I floated it left and gave the <code>div</code> a 90px left margin. That way, everything gets layed out perfectly, and this paragraph's text wraps.</p>
  </div>
</article>

Upvotes: 0

Bazzz
Bazzz

Reputation: 26922

Try white-space: normal on the li elements.

white-space is inherited by default so they received nowrap from the ul.

I'm starting to think that you are using an ul for layout purposes which div might be better suited for:

<div class="Item">
 <div class="ImageContainer"><img src="" alt="/></div>
 <div class="TextContainer">Text text text text text</div>
</div>

.Item {
 width: 200px;
 overflow: auto;
}

.ImageContainer {
 float: left;
 width: 40%;
}

.TextContainer {
 float: left;
 width: 60%;
}

Upvotes: 6

Related Questions