元素居中对齐
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>元素居中对齐</title>
<style>
</style>
</head>
<body>
实现元素居中对齐的两种方式
第一种,利用flex和align实现,实现简便,但是不支持ie9及以下的版本
<div style="width:200px;background: red;height: 100px;display:flex;align-items: center;">
<button style="width:50px;background: blue;height: 20px;margin: 0 auto;">按下</button>
</div>
第二种,利用margin和auto实现,auto是相对于剩余的空间设置margin值,不过得把前后左右的margin都先设置为0
支持ie9及以下的版本
<div style="width:200px;background: black;height: 100px; position: absolute;margin:auto;">
<button style="width:50px;background: blue;height: 20px; top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
margin:auto;">按下</button>
</div>
</body>
</html>
效果图