skip to Main Content

I have a list whose width is set in pixels. It has two list items: One whose content is shorter than the list, and one whose content extends past the width.

How can I make it so that the list items each have a width equal to the larger of the list width and the list item content width (so that the second item in this example contains its content)?

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

ul {
  width: 400px;

  overflow-x: scroll;
  outline: 1px dashed red;
}

li {
  max-width: none;
  min-width: 100%;

  padding: 0.5rem 1rem;

  white-space: nowrap;
  background-color: skyblue;
  outline: 1px dashed blue;
}
<ul>
  <li>test</li>
  <li>test test test test test test test test test test test test test test test test test test test test</li>
</ul>

2

Answers


  1. You can use display: inline-block instead of display: block so the width of the list is wrap to the content

    Sample below:

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    ul {
      width: 400px;
      overflow-x: scroll;
      outline: 1px dashed red;
    }
    
    li {
      /* Inline block's default width is wrap to the content, but there's also other differences between inline-block and block */
      display: inline-block;
      min-width: 100%;
      padding: 0.5rem 1rem;
      white-space: nowrap;
      background-color: skyblue;
      outline: 1px dashed blue;
    }
    <ul>
      <li>test</li>
      <li>test test test test test test test test test test test test test test test test test test test test</li>
    </ul>

    Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/display

    Login or Signup to reply.
  2. make the container display: grid and both items will extend to the largest one

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    ul {
      width: 400px;
      display: grid;
    
      overflow-x: scroll;
      outline: 1px dashed red;
    }
    
    li {
      padding: 0.5rem 1rem;
    
      white-space: nowrap;
      background-color: skyblue;
      outline: 1px dashed blue;
    }
    <ul>
      <li>test</li>
      <li>test test test test test test test test test test test test test test test test test test test test</li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search