1

li {
  background-color: yellow;
}
<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

I want to make the list items have both a background-color and a width no longer than their content. But if I add the display: inline-block property to them, then they all will appear next to each other. How could I fix this?

darkchampionz
  • 1,174
  • 5
  • 24
  • 47

4 Answers4

2
li {width:max-content;}

might be what you look for :

li {
  background-color: yellow;
}

li {
  width: max-content;
  max-width: 90%;/*optionnal but usefull,  avoids them to grow too wide */
}
<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>  
  <li>Coffee & Milk & Coffee & Milk & Coffee & Milk & Coffee & Milk & Coffee & Milk & Coffee & Milk &</li>
</ul>

see this post to find out more : How do min-content and max-content work?

G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
  • Tbh, I didn't even know `max-content` exists. Why isn't it shown as a value in the `width` property here https://www.w3schools.com/cssref/pr_dim_width.asp – darkchampionz Nov 13 '20 at 19:24
  • @darkchampionz because that site is to *not use*. Check here: https://developer.mozilla.org/en-US/docs/Web/CSS/width – Temani Afif Nov 13 '20 at 20:06
  • Hello! The solution seemed to work at first but, as it turned out, it does not wrap the text. Is there any way to fix this too? Thanks – darkchampionz Nov 20 '20 at 01:04
  • @darkchampionz did you also set the max-width as in the example ? I added a longer li to show that it wraps ;) – G-Cyrillus Nov 20 '20 at 01:11
2

You can use span inside li tags

span {
  background-color: yellow;
}
<ul>
  <li><span>Coffee</span></li>
  <li><span>Tea</span></li>
  <li><span>Milk</span></li>
</ul>
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
1

Easiest way is to put the list item in a span.

<ul>
  <li><span>Coffee</span></li>
  <li><span>Tea</span></li>
  <li><span>Milk</span></li>
</ul>

li span {
  background-color: yellow;
}
0

The old float can do it here:

li {
  background-color: yellow;
  float:left;
  clear:left;
}
<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415