css-div水平垂直居中

css-div水平垂直居中


  • 微信扫码关注公众号 :前端前端大前端,追求更精致的阅读体验 ,一起来学习啊
  • 关注后发送关键资料,免费获取一整套前端系统学习资料和老男孩python系列课程
    在这里插入图片描述

base html

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

base style

  * {
            margin: 0;
            padding: 0;
        }

        .parent {
            border: 1px solid black;
            padding: 40px;
        }

        .child {
            border: 1px solid red;
        }

不定宽高

方式一:使用定位+transform


        .parent {
            position: relative;
            padding: 40px;
            border: 1px solid black;
        }

        .child {
            position: absolute;
            left: 50%;
            transform: translateY(-50%);
            border: 1px solid red;

        }

方式二:父元素使用flex布局

	display: flex;
    justify-content: center;

在这里插入图片描述

定宽高

  		 .parent {
            position: relative;
            border: 1px solid black;
            padding: 40px;
        }

        .child {
            width: 100px;
            height: 20px;
            position: absolute;
            left: 50%;
            margin-left: -50px;
            margin-top: -10px;
            border: 1px solid red;

        }
发布了396 篇原创文章 · 获赞 786 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/qq_42813491/article/details/102792564