Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position an <input> in the center of the <div>

My HTML looks like this:

<div class="item">
    <div class="check">
      <input type="checkbox">
    </div>
    <div class="descr"> ... </div>
    <div class="details"> ... </div>
</div>

How do I align the checkbox in the middle of the div.check, both horizontally and vertically? (the height of the ".item" div is dynamic)

like image 614
eagor Avatar asked Jul 02 '13 12:07

eagor


2 Answers

Here is an edit of Kilian Stinson code that does not require CSS3 support. Instead of translate I use em's:

HTML:

<div class="check">
      <input class="center" type="checkbox">
</div>

CSS:

.check {
    width: 40px;
    height: 80px;
    outline: 1px solid red;
    position: relative;
}

.center {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -.5em;
    margin-top: -.5em;
}

JSFiddle: http://jsfiddle.net/Yzhnf/4/

like image 125
Andrei Surdu Avatar answered Sep 21 '22 11:09

Andrei Surdu


Try to translate it with css3

HTML

<input class="center" type="checkbox">

CSS

.check {
    position: relative;
}

.center {
    position: absolute;
    margin: 0;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

See this Fiddle with a working example.

At first, the element is positioned 50% from the left and 50% from the top. Then it's set back 50% of its own width and height.

For browser support get more information on caniuse.com.

like image 25
Kilian Stinson Avatar answered Sep 22 '22 11:09

Kilian Stinson