Prevent flexbox list items changing width of paren

2020-04-30 03:37发布

问题:

I have a series of list items and some have a child list, containing sub navigation links. I'm using CSS to create a hover effect by having display: none on the child <ul> and then setting to display: block when hovering.

However this has the undesired effect of making the parent <li> grow during hover. Is there a way to prevent this? When hovering over the <li> items that have no child lists then their width remains the same.

<ul class="flex unstyled-list">
  <li><a href="/">link</a></li>
  <li><a href="/" target="_blank">link 2</a></li>
  <li>
    <a href="/">parent 1</a>
    <ul class="unstyled-list">
      <li><a href="/">Hgdfgdf</a></li>
      <li><a href="/">Hgdfgdf</a></li>
    </ul>
  </li>
  <li>
    <a href="/">parent 2</a>
    <ul class="unstyled-list">
      <li><a href="/">Hgdfgdf gdf ggf dfs</a></li>
      <li><a href="/">Hgdfgdf gdf gdf gfd</a></li>
    </ul>
  </li>
</ul>


.unstyled-list {
  margin: 0;
  padding: 0;
  list-style-type: none;
}

.flex {
  width: 970px;
  height: 37px;
  display: flex;
  flex: 1 0 auto;
  flex-basis: 100%;
  background-color: #000;
}

.flex li {
  flex-grow: 1;
  height: 37px;
  line-height: 37px;
  color: #fff;
  text-align: center;
}

#nav-strip li:hover {
  background-color: #000;
}

.flex li:hover ul {
  display: block;
}

.flex li a {
  display: block;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
}

.flex li ul {
  display: none;
  width: 200px;
  padding: 0;
}

.flex li ul li {
  width: 185px;
  height: 30px;
  line-height: 30px;
  padding: 0 0 0 15px;
  background: #000;
  text-align: left;
}

.flex li ul li:hover {
  background: #1e1d3f;
}

.flex li ul li a {
  display: block;
  font-size: 12px;
  font-weight: normal;
}

Runnable example:

https://jsfiddle.net/ndp1y79b/1/

回答1:

Thanks to @Temani Afif and @Pete - adding

positon: absolute;
top: 100%

on the child <ul> has fixed this issue. Thanks - much simpler than I thought it may have been!