Set the width of the child between the parent's width and the maximum width

I want to create a CSS menu with some restrictions:

  • height and width of parent are <div>

    unknown
  • number <li>

    unknown
  • <ul>

    must be at least <div>

    width
  • one line <li>

    should contain as much as possible <li>

    withmax-width

    <ul>

What I want:

what I want

The problem is that it actually <ul>

takes into account the initial width too much and doesn't expand. If you click Run Code Snippet, you will see it.

HTML can be changed; flexible and tricks are welcome; JS is discouraged; IE10 support 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>
      

Run codeHide result


+3


source to share


1 answer


Here's the problem with your approach:

  • ul

    is a child of div

    .
  • ul

    absolutely positioned within bounds div

    , since div

    is the closest positioned ancestor ( position: relative

    )
  • As a result, ul

    it cannot skip the width div

    that is set to inline-block

    .
  • As such, elements li

    should be wrapped based on width div

    and max-width

    ignored.

I suggest you try a different method.

With pure CSS and HTML elements, table

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>
      

Run codeHide result


jsFiddle

  • height and width of parent are <div>

    unknown NO PROBLEM
  • number <li>

    unknown NO PROBLEM
  • <ul>

    must be at least <div>

    width YES
  • one line <li>

    should contain as much as possible <li>

    with max-width

    <ul>

    YES
  • No JavaScript YES
  • IE10 support YES
+2


source







All Articles