Tim Tim - 2 months ago 11
CSS Question

CSS to vertically align text in middle position beside a large checkbox

I want to have a checkbox 2em high, 2em wide, and next to it some extra small text in parentheses:

(check box to agree to these terms)


xxxxxxxxxxx
xxxxxxxxx∎x
xxxxxxx∎xxx
xxxxxx∎xxxx (check box to agree to these terms)
x∎xx∎xxxxxx
xxx∎xxxxxxx




#container {
height: 3em
}
input {
height: 2em;
width: 2em
}
.legal {
vertical-align: middle
}

<div id="container">
<input type="checkbox">
<div class="legal">(check box to agree to these terms)</div>
<div>





I've not had any success getting the text to move vertically by enclosing both in a container div, setting its height, and using
vertical-align: middle
on the text.

Answer

There are many ways to do it- see some of them below:

Solution 1: Inline-block

Use inline-block for both the input and the legal elements and vertically align them to the middle:

#container {
  height: 3em
}
input {
  height: 2em;
  width: 2em;
  display: inline-block;
  vertical-align: middle;
}
.legal {
  display: inline-block;
  vertical-align: middle;
}
<div id="container">
  <input type="checkbox">
  <div class="legal">(check box to agree to these terms)</div>
  <div>

Solution 2: Table display

Use table for the container and table-cell for both the input and the legal elements:

#container {
  height: 3em;
  display: table;
}
input {
  height: 2em;
  width: 2em;
  display: table-cell;
  vertical-align: middle;
}
.legal {
  display: table-cell;
}
<div id="container">
  <input type="checkbox">
  <div class="legal">(check box to agree to these terms)</div>
  <div>

Solution 3: Flexbox

Simply use flex for the container and use align-items: center to vertically center them:

#container {
  height: 3em;
  display: flex;
align-items: center;
}
input {
  height: 2em;
  width: 2em;
}
.legal {
}
<div id="container">
  <input type="checkbox">
  <div class="legal">(check box to agree to these terms)</div>
  <div>