元素居中问题

元素居中问题(横向&纵向)

参考:CSS实现垂直居中的常用方法
参考:父元素高度为auto:子元素使用top:-50%没有效果的问题
w3c的文档说

The offset is a percentage of the containing block’s width (for ‘left’ or ‘right’) or height (for ‘top’ and ‘bottom’). For ‘top’ and ‘bottom’, if the height of the containing block is not specified explicitly (i.e., it depends on content height), the percentage value is interpreted like ‘auto’.
如果父元素的高度没有明确指定,top 的值跟设定为auto的效果是一样的 。

即:若设相对长度%,外层父元素必须要有高度

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>flex 居中</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html,body {
         /* 外层环境要有高度才有作用 */
            height: 100%;
            width: 100%;
            display: flex;
             /* 主轴方向居中 */
            justify-content: center;
            /* 交叉轴方向居中 */
            align-items: center;

        }
        .bigbox {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 300px;
            height: 300px;
            border: 10px ridge red;
            /* --------常用老方法如下注释:-------- */
            /* margin: 0 auto; */
            /* position: relative;
            top: 50%;
            偏移自身高度的一半:
            transform: translateY(-50%); */
        }
        .smallbox {
            text-align: center;
            line-height: 100px;
            border: 1px solid #000;
            height: 100px;
            width: 100px;
        }
        </style>
</head>
<body>
   <div class="bigbox">
       <div class="smallbox">够不够居中</div>
       <div class="smallbox">文字如何</div>

   </div>
</body>
</html>

如图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值