2016-10-28 7 views
0

私は初心者としてCSSを学習しており、基本的なテストを行っています。私の質問は:下のCSSを見れば、box1の真ん中にbox2を配置する方法は?CSS - あるボックスを別のボックスに完全に配置するにはどうすればいいですか?

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

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

最初はボックス2にマージンオートを与えて、ボックス2が上下から等距離になると思っていましたが、この結果が得られます。

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/

関連する問題