Conditional width with CSS

css, html

Solution

The general sibling selector(`~`) does exactly what you want. It basically selects the second element only if preceded by the first element.

Try it like this:

.field label {
  width:25%;
}

/* Default style */
.field input {
  width:100%;
}

/* If preceded by a label, input gets different style */
.field label ~ input {
  width:75%;
}
<div class="field">
  <label>Label</label>
  <input type="text" name="" value="">
</div>

<div class="field">
  <input type="text" name="" value="">
</div>

Update: Just realized that you could also use the adjacent sibling selector(`+`) IF the `label` is guaranteed to immediately precede the input. General sibling selectors(`~`) are a part of CSS3 so might not work in incompatible browsers, while adjacent sibling selectors(`+`) are a part of CSS2.

Problem

``` <div class="field"> <label>Label</label> <input type="text" name="" value=""> </div> <div class="field"> <input type="text" name="" value=""> </div> ``` Is there any way I could set width on input conditionally based on label. So if label exists: ``` .field label { width:25%; } .field input { width:75%; } ``` else: ``` .field input { width:100%; } ``` I could do it with javascript but wanted to know if its possible with CSS only.

Original source