CSS未知寬高的元素,水平垂直居中
阿新 • • 發佈:2019-01-12
方法一:使用定位
思路:子元素絕對定位,距離頂部 50%,左邊50%,然後使用css3 transform:translate(-50%; -50%)
優點:高大上,可以在webkit核心的瀏覽器中使用
缺點:不支援IE9以下不支援transform屬性
<style> .parent{ position: relative; height:300px; width: 300px; background: #FD0C70; } .parent .child{ position: absolute; top: 50%; left: 50%; color: #fff; transform: translate(-50%, -50%); } </style> <body> <div class="parent"> <div class="child">hello world</div> </div> </body>
方法二:使用彈性佈局
思路:使用css3 flex佈局
優點:簡單 快捷
缺點:相容不好
<style> .parent{ display: flex; justify-content: center; align-items: center; width: 300px; height:300px; background: #FD0C70; } .parent .child{ color:#fff; } </style> <body>div> <div class="parent"> <div class="child">hello world</div> </div> </body>