0

CSS を使用して、div 内にある 2 つの「ボックス」を水平方向に中央揃えにしたいと考えています。ボックスは完全に配置されています。

これがJSFiddleです:http://jsfiddle.net/p4sA3/8/

特定の幅を使用せずにこれを達成するにはどうすればよいですか?

HTML:

<button id="change">Change</button>
<div id="total-wrap">
    <div id="hello-wrap" class="bunch">
        <div id="box"> 
            <p> Hello, this is text1 </p>
        </div>
        <div id="box">
            <p> Hello, this is text2 </p>
        </div>
    </div>
    <div id="goodbye-wrap" class="bunch">
        <div id="box"> 
            <p> Goodbye, this is text1 </p>
        </div>
        <div id="box">
            <p> Goodbye, this is text2 </p>
        </div>
    </div>
</div>

CSS:

#total-wrap {
    border:1px solid #000;
    height:500px;
}
#box {
    position:relative;
    display:inline-block;
    width:300px;
    height:100px;
    background-color:yellow;
    margin:10px;
}
.bunch {
    position: absolute;
    text-align:center;
}
4

5 に答える 5

0

jQuery を使用する場合:

デモ

keepCentered = function() { 
    $('#hello-wrap').css({'margin-left':($('#total-wrap').width()-$('#hello-wrap').width())/2});
    $('#goodbye-wrap').css({'margin-left':($('#total-wrap').width()-$('#goodbye-wrap').width())/2});
}
$(document).ready(keepCentered);
$(window).bind('resize', keepCentered);
于 2013-05-25T19:44:57.120 に答える
0

これは、あなたの望むことですか?

#box {
    position:relative;
    display:inline-block;
    width:100px;
    height:100px;
    background-color:yellow;
    margin:10px;
}

デモ: http://jsfiddle.net/p4sA3/11/

問題は、幅の合計がコンテナーを超える限り、2 番目の div が最初の div の下に配置されることです。

この他のデモでは、幅を使用しませんでした: http://jsfiddle.net/p4sA3/13/

于 2013-05-25T19:36:05.720 に答える