父元素为一个div,宽度高度不固定,子元素是一个块状元素,宽高已知,如何实现子元素在父元素内水平、垂直居中?

父元素为一个div,子元素是一个块状元素,宽高已知,如何实现子元素在父元素内水平、垂直居中?
 1、

//利用相对定位,让子元素垂直居中

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>
<style type="text/css">
    .parent-div {
        height: 600px;
        width: 600px;
        border: 1px solid red;
    }

    .child-div {
        height: 200px;
        width: 200px;
        border: 1px solid blue;
        margin: 0 auto;
        position: relative;
        top: 50%;
        margin-top: -100px;
    }
</style>

<body>
    <div class="parent-div">
        <div class="child-div"></div>
    </div>
</body>

</html>

2、//利用Flex(弹性布局)让子元素居中

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>
<style type="text/css">
    .parent-div {
        height: 600px;
        width: 600px;
        border: 1px solid red;
        display: flex;
        align-items: center;
        /* 垂直居中 */
        justify-content: center;
        /* 水平居中 */
    }

    .child-div {
        background-color: blue;
        height: 150px;
        width: 150px;
        /*margin:0 auto;*/
    }
</style>

<body>
    <div class="parent-div">
        <div class="child-div"></div>
    </div>
</body>

</html>

3、利用transform属性实现子元素(宽高未知)水平垂直居中;

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>
<style type="text/css">

    .parent-div {
        height: 600px;
        width: 600px;
        background-color: #ABCDEF;
    }

    .child-div {
        width: 180px;
        height: 180px;
        background-color: #000;
        position: relative;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
</style>

<body>
    <div class="parent-div">
        <div class="child-div"></div>
    </div>
</body>

</html>

以上三种方法是常见的水平垂直居中的。其中Flex是当下使用的比较多的一种布局方式,但是Flex并不是所有浏览器都支持。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值