如何让div中的div居中

<div>

<div >我要居中</div>

<div>

阅读 4.1k
4 个回答

方案一

父级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>

最外层的DIV给个宽度,里面的div给个margin: 0 auto

还有 flex布局中的居中

//外层div
display:flex;
justify-content:center;
align-items:center;
<style>
.main .son{
    text-align:center;
}
</style>

<div class="main">
    <div class="son">我要居中</div>
<div>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题