Search code examples
htmlcsswidth

Adaptive input width css


I'm having a problem with the text input, can it be made 'adaptive'? If I add the input are width, there will be too much unnecessary space in the left side. Again, if it's not wide enough, you can't see the whole input.

width set to 50px

too much space in left, if the input is short

        input[type="text"]{
        max-width: 50px;
        border: none;
        background: transparent;
        font-size: 20px;
        color: whitesmoke;
        padding: 5px;
        font-weight: bold;
        }

<input type="text" id="answer5" disabled="disabled"/>

Is there a way to make the area 'adaptive'? So if the answer is just 1, the text in the right is closer to the number, and if the answer is longer, you could see the whole answer.

thanks


Solution

  • You can handle this using a flex container and flex-grow: 1 for the child element which should take up the most available space.

    .container {
      display: flex;
      align-items: center;
    }
    
    .container [type="text"] {
      flex-grow: 1;
      margin: 0 .5em;
    }
    
    input[type="text"] {
      border: none;
      background: transparent;
      padding: 5px;
      font-weight: bold;
      border: 1px solid #333;
      padding: .5em.75em;
    }
    <div class="container">
      <label for="textInput" class="first">The following number:</label>
      <input type="text" id="textInput">
      <span class="result">is numeric</span>
    </div>

    jsFiddle