Ruslan
Ruslan

Reputation: 1303

Set a child's width between parent's width and max-width

I want to build a CSS menu with some restrictions:

  1. height and width of the parent <div> are unknown
  2. the number of <li> is unknown
  3. <ul> must be not smaller than <div> width
  4. one row of <li> must contain as many <li> as possible with max-width of <ul>

What I want:

what I want

The problem is: actually <ul> respects initial width too much and doesn't expand. If you click 'Run the code snippet', you will see it.

HTML can be changed; flex and tricks are welcome; JS is not welcome; IE10 support is required.

div {
  background: yellow;
  display: inline-block;
  padding: 20px 30px;
  position: relative;
}

ul {
  background: lightblue;
  left: 0;
  margin: 0;
  max-width: 450px;
  min-width: 100%;
  padding: 0;
  position: absolute;
  top: 100%;
}

li {
  background: orange;
  display: inline-block;
  margin: 2px;
  padding: 20px 25px;
}
<div>Stabat mater dolorosa
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
</div>

Upvotes: 3

Views: 4287

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371113

Here's the problem with your approach:

  • The ul is a child of the div.
  • The ul is absolutely positioned within the boundaries of the div, because the div is the nearest positioned ancestor (position: relative)
  • As a result, the ul cannot extend past the width of the div, which is set to inline-block.
  • So the li items must wrap based on the width of the div and the max-width is ignored.

I suggest you try a different method.

With pure CSS and HTML table elements all your requirements can be met.

tr:first-child td span {
  display: inline-block;
  padding: 20px 30px;
  background: yellow;
}

tr:last-child td {
  max-width: 450px;
}

ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
  background-color: lightblue;
}

li {
  background: orange;
  display: inline-block;
  margin: 2px;
  padding: 20px 25px;
}
<table>
  <tr>
    <td><span>Stabat mater dolorosa</span></td>
  </tr>
  <tr>
    <td>
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
      </ul>
    </td>
  </tr>
</table>

jsFiddle

  1. height and width of the parent <div> are unknown NO PROBLEM
  2. the number of <li> is unknown NO PROBLEM
  3. <ul> must be not smaller than <div> width YES
  4. one row of <li> must contain as many <li> as possible with max-width of <ul> YES
  5. No JavaScript YES
  6. IE10 support YES

Upvotes: 3

Related Questions