<div class="wrap">
<div class="center"></div>
</div>
CSS Code复制内容到剪贴板
/* css */ .wrap { background: yellow; width: 200px; height: 200px; display: flex; align-items: center; justify-content: center;
} .center { background: green; width: 100px; height: 100px;
}
移动端首选
方法五:display:flex;margin:auto
XML/HTML Code复制内容到剪贴板
<!– html –>
<div class="wrap">
<div class="center"></div>
</div>
CSS Code复制内容到剪贴板
/* css */ .wrap { background: yellow; width: 200px; height: 200px; display: flex;
} .center { background: green; width: 100px; height: 100px; margin: auto;
}
移动端首选
方法六:纯position
XML/HTML Code复制内容到剪贴板
<!– html –>
<div class="wrap">
<div class="center"></div>
</div>
CSS Code复制内容到剪贴板
/* css */ .wrap { background: yellow; width: 200px; height: 200px; position: relative;
} /**方法一**/ .center { background: green; position: absolute; width: 100px; height: 100px; left: 50px; top: 50px;
} /**方法二**/ .center { background: green; position: absolute; width: 100px; height: 100px; left: 50%; top: 50%; margin-left:-50px; margin-top:-50px;
}
兼容性:适用于所有浏览器
方法六中的方法一计算公式如下:
子元素(conter)的left值计算公式:left=(父元素的宽 – 子元素的宽 ) / 2=(200-100) / 2=50px;
子元素(conter)的top值计算公式:top=(父元素的高 – 子元素的高 ) / 2=(200-100) / 2=50px;
方法二计算公式:
left值固定为50%;
子元素的margin-left= -(子元素的宽/2)=-100/2= -50px;
top值也一样,固定为50%
子元素的margin-top= -(子元素的高/2)=-100/2= -50px;










