子元素分为很多情况:
定宽定高
方法一
1 <style> 2 .father { 3 width: 300px; 4 height: 300px; 5 position: relative; 6 background-color: antiquewhite 7 } 8 .child { 9 width: 100px; 10 height: 100px; 11 background-color: aqua; 12 position:absolute; 13 top: 50%; 14 left: 50%; 15 margin: -50px 0 0 -50px; 16 } 17 </style> 18 19 <body> 20 21 <div class="father"> 22 <div class="child"> 23 </div> 24 </div> 25 26 </body>
方法二
<style> .father { width: 300px; height: 300px; position: relative; background-color: antiquewhite } .child { width: 100px; height: 100px; background-color: aqua; position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; } </style> <body> <div class="father"> <div class="child"> </div> </div> </body>
不定宽高
方法一 absolute + translate
<style> .father { width: 300px; height: 300px; position: relative; background-color: antiquewhite } .child { width: 100px; height: 100px; background-color: aqua; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } </style> <body> <div class="father"> <div class="child"> </div> </div> </body>
方法二 flex
①
<style> .father { width: 300px; height: 300px; display: flex; background-color: antiquewhite } .child { width: 100px; height: 100px; background-color: aqua; margin: auto; } </style> <body> <div class="father"> <div class="child"> </div> </div> </body>
②
<style> .father { width: 300px; height: 300px; display: flex; background-color: antiquewhite; justify-content: center; align-items: center; } .child { width: 100px; height: 100px; background-color: aqua; } </style> <body> <div class="father"> <div class="child"> </div> </div> </body>
行内元素:
<style> .father { width: 300px; height: 300px; background-color: antiquewhite; text-align: center; line-height: 300px } .child { background-color: aqua; } </style> <body> <div class="father"> <span class="child"> 天天开心身体健康学业进步 </span> </div> </body>