relative定位无法上下左右居中?

html结构

<div class="box">
</div>

css

.box{
position:relative;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
width:100px;
height:100px;
border:1px solid red;
}

当position是absolute或者fixed时,box可以上下左右居中,为何position是relative时,无法上下左右居中(可以左右,无法上下)?
我测试过了,relative定位的时候,left,right,top,bottom也都可以作用的。

阅读 2.2k
3 个回答
当position是absolute或者fixed时,box可以上下左右居中是因为

如果父级属性未设置position则默认为body,他们都是根据body去定位的, left、right、top、bottom属性指的是距body的左边右边上边下边的距离。

relative的left、right、top、bottom属性是相当于自身的

relative 是相对于当前位置。所以 0 的含义是不动

position: relative;
bottom: 21px; /* 意味着向上挪 */

至于你说的居中,那是 margin 的功劳,如下代码也是可以水平居中的

.box{
margin:auto;
width:100px;
height:100px;
border:1px solid red;
}

简单的水平居中可以用 text-align, margin: 0 auto

现在我觉得flex布局更简单

<style>
    .cc {
        width: 300px;
        height: 300px;
        display: flex;
        justify-content: center;
    }
    .cc2 {
        display: flex;
        flex-direction: column;
        justify-content: center;
    }



</style>


<div class="cc">
    <div class="cc2">
        <span class="cc3">居中显示</span>
    </div>
</div>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题