Vertically center a checkbox within a div

15,672

Solution 1

check this jsFiddle

HTML

<div id="read-confirm-box">
  I Have read the above 
  <input type="checkbox" id="checkbox" />
</div>

CSS

#read-confirm-box
{
    color: #FFF;
    width: 180px;
    font-size: 12px;
    background-color: #333;
    border-radius: 3px;
    padding: 6px 11px;
    margin: auto;
    float: left;
}

#checkbox 
{
    position: relative;
    top: 3px;
}

Solution 2

You can wrap both text and input into a div, It's a good practice.

To align both the divs containing text and control accordingly, use display properties

Try:

HTML

<div id="read-confirm-box">
    <div class="inline">I Have read the above </div>
    <div class="inline"><input type="checkbox" id="checkbox" /></div>
</div>

 <label for="checkbox">I Have read the above </label>
 <input type="checkbox" id="checkbox" />

<span>I Have read the above </span>
<span><input type="checkbox" id="checkbox" /></span>

CSS

.inline{
    display:inline-block;
    vertical-align:middle;
}

Fiddle Example

Updated

Share:
15,672
John 'Mark' Smith
Author by

John 'Mark' Smith

I have come to ask questions.

Updated on June 05, 2022

Comments

  • John 'Mark' Smith
    John 'Mark' Smith almost 2 years

    I have a checkbox within a div that is appearing higher than the text I want it to be aligned with.

    Here's how it appears in Firefox:

    enter image description here

    As you can see, the checkbox is just a few pixels higher than the text. I have tried applying various padding / margins, including negative values, but to no avail.

    HTML:

    <div id="read-confirm-box">
      I Have read the above 
      <input type="checkbox" id="checkbox" />
    </div>
    

    CSS:

    #read-confirm-box
    {
        color: #FFF;
        width: 180px;
        font-size: 12px;
        background-color: #333;
        border-radius: 3px;
        padding: 6px 11px;
        margin: auto;
        float: left;
    }
    
    #checkbox 
    {
        /* Empty */
    }
    
  • Paulie_D
    Paulie_D about 10 years
    Only works with multiple elements that have display:inline-block
  • Paulie_D
    Paulie_D about 10 years
    Logically the first div should be a `<label>. :)
  • Dhaval Marthak
    Dhaval Marthak about 10 years
    Yeah <label for=''> :)
  • Hashem Qolami
    Hashem Qolami about 10 years
    Better to use <span> element as an inline wrapper.
  • Hashem Qolami
    Hashem Qolami about 10 years
    @Paulie_D You could verify that: Another example including an image jsbin.com/hedag/3/edit
  • Hashem Qolami
    Hashem Qolami about 10 years
    I didn't. But it depends on the size of the font: jsfiddle.net/hashem/vcM56/3
  • Ted
    Ted about 10 years
    >Hashem...As does the accepted answer... >Dhaval yes, vertical-align can take a value of measurement
  • Mason
    Mason almost 7 years
    Doesn't work when that's the only css you apply on the checkbox.