块级元素在块级元素内部垂直居中

步骤:

1、给父级元素添加相对定位position:relative;

2、子元素设置如下:

  position: absolute;

  left: 50%;

  top: 50%;

  //设置为子元素width的一半,设置为负值

  margin-left: -25px;

  //设置为子元素height的一半,设置为负值

  margin-top: -25px;

代码案例如下:

<!DOCTYPE html>
<html>
<head>
    <title>块级元素在块级元素内部垂直居中</title>
</head>
<style type="text/css">
    .external{
        width: 100px;
        height: 100px;
        background-color: red;
        position: relative;

    }
    .internal{
        width: 50px;
        height: 50px;
        background-color: blue;
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -25px;
        margin-top: -25px;

    }
</style>
<body>
    <div class="external">
        <div class="internal"></div>
    </div>

</body>
</html>

 

posted @ 2018-04-18 09:58  呀,西蓝花  阅读(176)  评论(0编辑  收藏  举报