CSS练习题——1.正方形居中圆

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_40686529/article/details/102694643

目录

 

1.技术点

2.需求              ​

3.步骤

4.完整代码


1.技术点:

  1. margin居中
  2. transform居中

2需求              

3.步骤:

   3.1 首先布局很简单:

        .circle{
            width: 400px;
            height: 400px;
            border-radius: 400px;
            margin: 100px auto;
            border: 1px solid #000;
            position: relative;
        }
        .square{
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
        }

如上,效果只能做到这样

扫描二维码关注公众号,回复: 7645211 查看本文章

   3.2 然后就想移动正方形,使正方形中心与圆心重合,首先想到的是

margin:0 auto;

然而如此做,只能使水平居中,当使用

margin:auto auto;

在垂直方向却无法做到居中

  3.3. 处理方法

    如果使用

left: 50%;
top: 50%;

则能把正方形相对于圆上下移动50%

3.4. 然而需求是正方形中心与圆心重合,下面如果我们能把正方形相对于自己向左上移动50%,那么就能达到需求

使用

tranform: translate(-50%,-50%);

完成

4.完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>圆与正方形居中</title>
    <style type="text/css">
        .circle{
            width: 400px;
            height: 400px;
            border-radius: 400px;
            margin: 100px auto;
            border: 1px solid #000;
            position: relative;
        }
        .square{
            width: 100px;
            height: 100px;
            background: red;
            margin: 0 auto;
            left: 50%;
            top:50%;
            position: absolute;
            transform:translate(-50%,-50%);
        }
    </style>
</head>
<body>
    <div class="circle">
        <div class="square"></div>
    </div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_40686529/article/details/102694643
今日推荐