Gustavo
Gustavo

Reputation: 21

Right align input labels

The example below shows a minimum working example for aligning labels right to an input. Is there any way to make an input to take 100% width? Another intended use case is to replace an input with a textarea or any other div with variable height.

<!DOCTYPE html5>
<html>
    <head>
        <style>
div.a {
    flex:1 1;
}

div.b {
    flex:1 1;
}

div.form {
    /*display: table;*/
    width: 100%;
}

div.form div {
    display: table-row;
    width: 100%;
}

div.form div label {
    display: table-cell;
    text-align: right;
    padding-right: 5px; 
}

div.form div input {
    width: 100%;
}

        </style>
    </head>
    <body>
        <div style="display:flex">
            <div class="a">
                <div class="form">
                    <div>
                        <label>a</label>
                        <input/>
                    </div>

                    <div>
                        <label>askldak  asd ls</label>
                        <input/>
                    </div>
                    <div>
                        <label>askldakasda   asdls</label>
                        <input/>
                    </div>
                </div>
            </div>
            <div class="b">b</div>
        </div>
    </body>
</html>

Edit 1

Example from the second post

I've tried the example but the labels were not aligned as expected.

Upvotes: 2

Views: 80

Answers (1)

dippas
dippas

Reputation: 60543

you can achieve that using flexbox

.form div {
  display: flex
}
.form div input {
  flex: 1
}
<div>
  <div class="a">
    <div class="form">
      <div>
        <label>a</label>
        <input/>
      </div>

      <div>
        <label>askldak asd ls</label>
        <input/>
      </div>
      <div>
        <label>askldakasda asdls</label>
        <input/>
      </div>
    </div>
  </div>
  <div class="b">b</div>
</div>

If you want label to have the same size, then you can do this:

.form div {
  display: flex
}
.form div label {
  flex: 1
}
.form div input {
  flex: 4
}
<div>
  <div class="a">
    <div class="form">
      <div>
        <label>a</label>
        <input/>
      </div>
      <div>
        <label>askldak asd ls</label>
        <input/>
      </div>
      <div>
        <label>askldakasda asdls</label>
        <input/>
      </div>
    </div>
  </div>
  <div class="b">b</div>
</div>

Upvotes: 1

Related Questions