2016-10-28 124 views
0

我正在學習css作爲初學者和做一些基本的測試。我的問題是:給出下面的CSS我怎樣才能將box2放在box1的中間?CSS - 如何將一個盒子完全居中在另一個盒子中?

.box1 { 
    background: black; 
    height: 400px; 
    width: 400px; 
    margin: auto; 
} 

.box2 { 
    height:300px; 
    width:300px; 
    background: red; 
    margin: auto; 
} 

在開始的時候我還以爲給BOX2保證金自動所以BOX2是從頂部和底部的距離相等,但我得到這個結果。

enter image description here

它看起來像它設置爲左,右,但不是頂部和底部的邊距汽車。

所以,如果我給我一個保證金最高我自己就這樣工作。

enter image description here

代碼:

.box2 { 
    margin: 20px auto; 
} 

我怎麼能這樣做BOX2在BOX1完全居中?

回答

0

.box1 { 
 
background: black; 
 
height: 400px; 
 
width: 400px; 
 
margin: auto; 
 
} 
 

 
.box2 { 
 
height:300px; 
 
width:300px; 
 
background: red; 
 
position:relative; 
 
left:12.5%; 
 
top:12.5%; 
 
}
<div class="box1"> 
 
<div class="box2"> 
 

 
</div> 
 
</div>

嘗試。

0

.box1 { 
 
background: black; 
 
height: 400px; 
 
width: 400px; 
 
display:flex; 
 
justify-content:center; 
 
align-items: center; 
 
} 
 

 
.box2 { 
 
height:300px; 
 
width:300px; 
 
background: red; 
 
}
<div class="box1"> 
 
<div class="box2"></div> 
 
</div>

0

可以使用flexbox

.box1 { 
 
    background: black; 
 
    height: 400px; 
 
    width: 400px; 
 
    margin: auto; 
 
    display:flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
} 
 

 
.box2 { 
 
    height:300px; 
 
    width:300px; 
 
    background: red; 
 
    margin: auto; 
 
}
<div class="box1"> 
 
    <div class="box2"> 
 
    </div> 
 
</div>

2
.box1 { 
    position:relative; 
    background: black; 
    height: 400px; 
    width: 400px; 
    margin: auto; 
} 

.box2 { 
    position:absolute; 
    height:300px; 
    width:300px; 
    background: red; 
    left:50%; 
    top:50%; 
    transform: translate(-50%, -50%); 
} 

檢查小提琴做到這一點:https://jsfiddle.net/wh4yqk2y/