繁体   English   中英

中间将另一个div中的div与中间指定内容对齐

[英]middle aligning a div inside another div with middle alligned content

我有两个div,一个在另一个内,而内部div的ap标签中间对齐。 标记为

<div class="box1">
    <div class="box2">
        <p>hello</p>
    </div>
</div>

样式规则是

.box1 {
    width: 400px;
    height: 400px;  
    background: red;
    text-align: center;
}
.box2 {
    display: table-cell;
    width: 200px;
    height: 200px; 
    margin: auto;
    vertical-align: middle; 
    text-align: center;   
    background: yellow;
}

我想做的是将p标签在内部div(box2)内垂直和水平居中,将内部div垂直和水平居中于外部div(box1)居中。 我未能将内部div(box2)置于外部div的中心。 请帮我做。 我为此创建了一个小提琴-> http://jsfiddle.net/64WAW/1/

请看这个:

http://jsfiddle.net/itz2k13/64WAW/2/

.box1 {
 display: table-cell;
 width: 400px;
 height: 400px;  
 background: red;
 text-align: center;
 vertical-align: middle;
}

.box2 {    
 width: 200px;
 height: 200px; 
 background: yellow;
 margin: auto;
 line-height: 200px;
}

HTML:

<div class="box1">
    <div class="box2container">
        <div class="box2">
            <p>hello</p>
        </div>
    </div>
</div>

CSS:

.box1 {
    width: 400px;
    height: 400px;  
    background: red;
    text-align: center;
}
.box2 {
    position:relative;
    top:-50%;
    left:-50%;
    width: 200px;
    height: 200px; 
    background: yellow;
    line-height:200px;
}

.box2container{
    width: 200px;
    height: 200px; 
    position:relative;
    top:50%;
    left:50%;
}

此解决方案避免使用旧浏览器不支持的display:table-cell 查看小提琴

您将使用flexbox,这很容易。它是这样的:

.box1,
.box2{
  display: -moz-box; /*Safari,  iOS, Android browser, older WebKit browsers. */
  display: -webkit-box;/* Firefox (buggy) */
  display: -ms-flexbox; /*IE 10*/
  display: -webkit-flex;/*Chrome 21+ */
  display: flex;/*Opera 12.1, Firefox 22+ */

  -webkit-box-align: center; 
  -moz-box-align: center;
  -ms-flex-align: center; 
  -webkit-align-items: center;
  align-items: center;
  -webkit-box-pack: center; 
  -moz-box-pack: center; 
  -ms-flex-pack: center; 
  -webkit-justify-content: center;
  justify-content: center;
}
.box1{
    width: 400px;
    height: 400px;  
    background: red;
    text-align: center;     
}
.box2 {
    background: yellow;
    width: 200px;
    height: 200px;
}

请观看演示 ,详细请看教程

使用display:inline-block并为其父容器添加:after

.box1 {
    width: 400px;
    height: 400px;  
    background: red;
    text-align: center;
}
.box2 {
    display: inline-block;
    width: 200px;
    height: 200px; 
    vertical-align: middle; 
    text-align: center;   
    background: yellow;
}
.box1:after {
  content:"";
  width: 1px;
  height: 100%;
  position: relative;
  display: inline-block;
  vertical-align: middle; 
}

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM