eagor
eagor

Reputation: 10065

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)

Upvotes: 5

Views: 11063

Answers (3)

Andrei Surdu
Andrei Surdu

Reputation: 2341

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/

Upvotes: 8

Kilian Stinson
Kilian Stinson

Reputation: 2394

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.

Upvotes: 3

czioutas
czioutas

Reputation: 1068

position:relative; margin-left:auto; margin-right:auto; top..bottom etc

if that doesnt work

position:absolute; left:50%; right:50%;

Upvotes: 0

Related Questions