方案一 父级div `text-align:center` 子级div `display: inline-block;` 方案二 // 子级div宽度未知(跟随子级内容变化而变化) <style> .wrapper { width: 100%; height:300px; background-color: #e6e6e6; } .wrapper .item { display: inline-block; position: relative; top:50px; left:50%; transform: translateX(-50%); padding: 10px; background-color: #505050; color:#fff; } </style> <div class="wrapper"> <span class="item" > 我要居中我要居中我要居中我要居中 </span> </div> 方案三 // 子级div宽度已知 <style> .wrapper { width: 100%; height:300px; background-color: #e6e6e6; } .wrapper .item { display: inline-block; position: relative; width: 300px; top:50px; left:50%; margin-left: -150px; padding: 10px; background-color: #3279a4; text-align: center; color:#fff; } </style> <div class="wrapper"> <span class="item" > 我要居中我要居中我要居中我要居中 </span> </div> 方案四 margin:auto 居中 <style> .pos-rlt { position: relative; width: 500px; height: 300px; background-color: #08c; } .pos-abt { position: absolute; top:0; left:0; right:0; bottom:0; width:200px; height:100px; background-color: #fff; margin: auto; } </style> <html> <!-- margin:auto 居中 参考张鑫旭的CSS世界 --> <div class="pos-rlt"> <div class="pos-abt"></div> </div> </html>
<style> .main .son{ text-align:center; } </style> <div class="main"> <div class="son">我要居中</div> <div>
方案一
方案二
方案三
方案四 margin:auto 居中