Home > Enterprise >  Prevent select HTML element from overflowing parent width
Prevent select HTML element from overflowing parent width

Time:10-09

I have a parent container with fixed length. It has two children: span and select. There's a problem that select overflows parent when option name is very long.

I would like the select to not grow past parent width.

Here's a codepen: https://codepen.io/dostu/pen/eYrPKjZ

EDIT: The select options are dynamic in my case. When they are short I would like to keep the select's original width and not fill the parent 100%.

.container {
  display: flex;
  align-items: center;
  width: 150px;
  height: 50px;
  background-color: #ddd;
}
<div >
  <span>Style</span>
  <select>
    <option>Very very very long option</option>
  </select>
</div>

CodePudding user response:

You can do this by adding a container around the <select> element with a min-width of 0 and then setting the max-width on the <select> to 100%.

The min-width: 0 on the container overrides the default min width for flex items and allows the container to shrink past the content size, as described in: Why don't flex items shrink past content size?.

The max-width: 100% on the <select> element prevents it from overflowing its container.

Here's an example (with both long and short option values):

.container {
  display: flex;
  align-items: center;
  width: 150px;
  height: 50px;
  background-color: #ddd;
}

.select-wrapper {
  min-width: 0;
}

select {
  max-width: 100%;
}
<div >
  <span>Style</span>
  <div >
    <select>
      <option>Very very very long option</option>
    </select>
  </div>
</div>

<div >
  <span>Style</span>
  <div >
    <select>
      <option>Opt</option>
    </select>
  </div>
</div>

CodePudding user response:

You can hide the overflow of the parent element, any element bigger than the parent element won't be visible past the parent size. You can as well set a max-width for the child element, so it doesn't go larger than the parent element.

I edited your codepen:

HTML

<div >
    <span>Style</span>
    <select >
        <option>Very very very long option</option>
    </select>
</div>

CSS

.container {
    display: flex;
    align-items: center;
    width: 150px;
    height: 50px;
    background-color: #ddd;
    overflow: hidden;
}

.option {
    max-width: 100px;
}
  • Related