Open Twlig opened 2 years ago
<style> #container{ display: block; width: 400px; height: 100vh; margin: 0 auto; position: relative; background-color: #B3C0D1; } .item { width: 200px; height: 300px; background-color: #42b983; display: block; position: absolute; top: 50%; left: 50%; transform:translate(-50%, -50%); } </style> <body> <div id="container"> <div class="item">1</div> </div> </body>
.item { width: 200px; height: 300px; background-color: #42b983; display: block; position: absolute; top: 50%; left: 50%; margin-left: -100px; margin-top: -150px; }
#container{ display: flex; width: 400px; height: 100vh; margin: 0 auto; background-color: #B3C0D1; justify-content: center; align-items: center; } .item { width: 200px; height: 300px; background-color: #42b983; }
#container{ display: grid; width: 400px; height: 100vh; margin: 0 auto; background-color: #B3C0D1; grid-template-columns: 100px; grid-template-rows: 100px; place-content: center; place-items: center; } .item { background-color: #42b983; width: 100%; height: 100%; }
实现垂直水平居中
方法一:采用position+transform:translate(-50%, -50%)
方法二:采用position+margin-left+margin-top
方法三:采用flex
方法四:采用grid