将元素垂直居中放置在页面的两侧

时间:2014-10-18 15:26:56

标签: html css

我有一个<div>元素,并希望将< div>垂直居中对齐到页面的左侧或右侧。

<div id="qrcode">Content</div>

以下是我试过的CSS:

#qrcode{
    position:absolute;
    left:100%;
    margin-top:200px;
    margin-left:-200px;
    width:80px;
    height:80px;
}

但是当<div>的大小发生变化时,这不能正常工作。 应该是什么属性,以便它可以工作,无论<div>的大小?

3 个答案:

答案 0 :(得分:1)

如果您想垂直居中对齐页面右侧的元素,您可以使用翻译技术,如:

&#13;
&#13;
#qrcode {
  position: absolute;
  top: 50%;
  right: 0; /*or left*/
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  -moz-transform: translateY(-50%);
  transform: translateY(-50%);
  width: 80px;
  height: 80px;
  background: hotpink;
}
&#13;
<div id="qrcode">Content</div>
&#13;
&#13;
&#13;

基本上,top:50%将元素的顶部定位在页面的垂直中心,translateY(-50%)50%向上推到y轴上,相对于它{39} ; s自己的大小 - 将其定位在页面的垂直中心。 right:0只是将其置于右侧。

答案 1 :(得分:0)

您可以轻松地将<div>像这样居中:

HTML:

<div id="qrcode">Content</div>

CSS:

#qrcode{
    background: black;
    color: white;
    width:80px;
    margin: 0px auto;
    height:80px;
}

<强> DEMO

答案 2 :(得分:0)

试试这个:

position: fixed;
margin: auto;
height: 80px;
top: 0;
bottom: 0;

并根据您的需要添加left: 0right: 0

&#13;
&#13;
.qrcode{
  position: fixed;
  margin: auto;
  height: 80px;
  top: 0;
  bottom: 0;
  background: red;
}
.qrcode.left {
  left: 0;
}
.qrcode.right {
  right: 0;
}
&#13;
<div class="qrcode left">Content</div>
<div class="qrcode right">Content</div>
&#13;
&#13;
&#13;

相关问题