CSS布局--垂直水平居中

it2022-05-09  36

···设置两个盒子

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

 

方法一:absolute

<!-- //父元素相对定位,子元素绝对定位 -->

<!-- //绝对定位盒子模型有个特点:left + right + width + padding + margin = 包含块的宽度;此时可以将left、right设置为0;padding、margin未设置是默认为0;所以将margin设置为auto,使得元素自动居中; -->

<style type="text/css"> *{   margin: 0;   padding: 0; } .parent{   position: relative;   width: 200px;   height: 200px;   border: 1px solid black; } .child{   position: absolute;   left: 0;   right: 0;   top: 0;   bottom: 0;   margin: auto;   width: 100px;   height: 100px;   background: pink; } </style>

 

方法二:absolute + 负margin

.parent{     position: relative;   width: 200px;   height: 200px;   border: 1px solid black;  } .child{   position: absolute;   left: 50%; top: 50%;   margin-left: -50px;   margin-top: -50px;   width: 100px;   height: 100px;   background: pink; } 方法三:flex布局   //只需设置父节点属性,无需设置子元素   // 父元素设置   display: flex;   justify-content:center;   align-items:Center;  

 

转载于:https://www.cnblogs.com/veraNotes/p/10885636.html


最新回复(0)