2016-08-27 6 views
2

私は3つのdiv(色のついた四角形)とボタンを持っています。3つのdivの下のボタンを中心に

divの下にボタンの中心を合わせるにはどうすればよいですか?

私の現在のコードでは、ボタンは#squaresと同じ行に表示され、左に浮いています。あなたの答えをありがとう。

#div1 { 
 
    background-color: red; 
 
    width: 100px; 
 
    height: 100px; 
 
    margin-right: 10px; 
 
} 
 
#div2 { 
 
    background-color: green; 
 
    width: 100px; 
 
    height: 100px; 
 
    margin-right: 10px; 
 
} 
 
#div3 { 
 
    background-color: blue; 
 
    width: 100px; 
 
    height: 100px; 
 
} 
 
#squares { 
 
    display: flex; 
 
    position: absolute; 
 
    margin-left: 35%; 
 
} 
 
#button { 
 
    width: 100px; 
 
    height: 50px; 
 
    clear: both; 
 
}
<div id="squares"> 
 
    <div id="div1"></div> 
 
    <div id="div2"></div> 
 
    <div id="div3"></div> 
 
</div> 
 
<div id="button"> 
 
    <button>Click me!</button> 
 
</div>

答えて

1

既にフレックスボックスを使用しているので、複数のソリューションがあり、すべて比較的簡単です。

は、ここに1つです:親コンテナ内

  • ラップ両容器。
  • display: flexflex-direction: columnをこの新しいコンテナに追加します。
  • 正方形とボタンを縦横に簡単に合わせることができます。

#container { 
 
    display: flex; 
 
    flex-direction: column; 
 
} 
 
#div1 { 
 
    background-color: red; 
 
    width: 100px; 
 
    height: 100px; 
 
} 
 
#div2 { 
 
    background-color: green; 
 
    width: 100px; 
 
    height: 100px; 
 
    margin: 0 10px; 
 
} 
 
#div3 { 
 
    background-color: blue; 
 
    width: 100px; 
 
    height: 100px; 
 
} 
 
#squares { 
 
    display: flex; 
 
    align-self: center; 
 
    margin-bottom: 10px; 
 
} 
 
#button { 
 
    align-self: center; 
 
    text-align: center; 
 
    width: 100px; 
 
    height: 50px; 
 
}
<div id="container"> 
 
    <div id="squares"> 
 
    <div id="div1"></div> 
 
    <div id="div2"></div> 
 
    <div id="div3"></div> 
 
    </div> 
 
    <div id="button"> 
 
    <button>Click me!</button> 
 
    </div> 
 
</div>

1

あなたは正方形のコンテナのposition: absoluteを使用している具体的な理由はありますか?

もしそうでない場合は、相対的な位置を決め、内容を再センタリングしてボタンを中央に置くことができます。

重要なコードはを変更します。

#squares { 
    position: relative; 
    justify-content: center; 
} 

#button { 
    margin: 0 auto; 
} 

フィドル:それを解決するためにhttps://jsfiddle.net/q17fa25w/

+0

感謝の男が、うまく動作します。 – bu246

0

他の方法、あなたは #button ため左と上パディングを設定することができますdivのように:

#button { 
    width: 100px; 
    height: 50px; 
    clear: both; 
    padding: 120px 35%; 
} 
関連する問題