zljiaa 2019-09-07
实现div在屏幕水平垂直居中的4个方法:
CSS:
<style> *{ margin: 0; padding: 0; } .div1 { position:absolute; width:200px; height:200px; top:50%; left:50%; margin-left:-100px; margin-top:-100px; background: yellow; } .div2 { width: 200px; height: 200px; background-color: pink; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; } .div3{ width: 200px; height: 200px; background-color: skyblue; position: absolute; top: calc(50% - 100px); /* 必须要有空格 */ left: calc(50% - 100px); } .div4{ width: 200px; height: 200px; background-color: red; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } </style>
HTML:
<!-- <div class="div1"></div> --> <!-- <div class="div2"></div> --> <!-- <div class="div3"></div> --> <div class="div4"></div>
如果你有更多更好的方法,欢迎亲们补充。