如何将<input>标签置于<div>中心位置

5

我的HTML代码如下:

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

如何将复选框在
中水平垂直居中对齐?(".item"div的高度是动态的)

1
display: table-cell; 这里是唯一的选项。 - Mr. Alien
2
Example - Vucko
3个回答

7
这是 Kilian Stinson 的代码编辑版,不需要支持 CSS3。我使用 em's 代替 translate

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/


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

3

试着用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%);
}

请看这个Fiddle,其中有一个工作示例。
首先,该元素被定位在距左侧和顶部各50%的位置。然后将其向后设置自身宽度和高度的50%。
如需浏览器支持,请访问caniuse.com获取更多信息。

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

如果那不起作用
position:absolute; left:50%; right:50%;

2
你可以使用margin:0 auto或者margin:auto;来代替单独命名它们。 - Jeff Noel
2
通过设置 position: absolute50%,它只会将左上角居中。 - Kilian Stinson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接