簡體   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