3zzy 3zzy - 1 month ago 5
CSS Question

Conditional width with CSS

<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.

Answer

General sibling selectors 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>