位置绝对位于div的中间位置

时间:2017-06-20 07:27:52

标签: javascript html css

大家好我在将位置设置为绝对后我无法将屏幕中间的div居中,我不想因为浏览器的兼容性而使用flexbox

<style>div{
height:200px;
width: 300px;
display:inline-block;
position: absolute;
background-color:red;
}
</style>
<div>
some content
</div>

https://codepen.io/anon/pen/KqWYQg

4 个答案:

答案 0 :(得分:3)

添加left:50%top:50%以及transform:translate(-50%, -50%)

这将使元素水平和垂直居中。这对于响应式设计也很有用,因为即使您调整浏览器大小,元素也会保持居中

div {
  height: 200px;
  width: 300px;
  display: inline-block;
  position: absolute;
  background-color: red;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div>
  some content
</div>

答案 1 :(得分:0)

您需要添加left: 50%;top: 50%;transform: translate(-50%, -50%);。 不要忘记使用前缀来跨浏览器兼容性。

div {
  height: 200px;
  width: 300px;
  position: absolute;
  background-color: red;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
<div>
  some content
</div>

答案 2 :(得分:0)

div{
    height:200px;
    width: 300px;
    display:inline-block;
    position: absolute;
    background-color:red;
    left:50%;
    transform: translateX(-50%); 
    }
<div>
some content
</div>

使用其他浏览器的兼容性

答案 3 :(得分:0)

您可以使用Absolute Horizontal And Vertical Centering,这是跨浏览器(适用于IE8),非常简单:

html, body {
  height: 100%;
  margin: 0;
}

div {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  height: 200px;
  width: 300px;
  background-color: red;
  margin: auto;
}
<div>
  some content
</div>