CSS定位div彼此相邻

时间:2013-03-19 18:03:01

标签: css

我在div中定位2个div时遇到问题。我希望彼此相邻2个div,但我不知道怎么做。这是我的HTML

<div id="game">
    <div id="choice" onmouseover="npcRoll()">
        <p>Chosse your weapon!</p>
        <button id="rock" onClick="choose(1)">Rock</button>
        <button id="paper" onClick="choose(2)">Paper</button>
        <button id="scissors" onClick="choose(3)">Scissors</button>
        <p>You chose <span id="userChoice">none</span>!</p>
    </div>
    <div id="confirm">    
    </div>
</div>

这是我的CSS:

#choice {
    border: 2px solid #87231C;
    border-radius: 12px;
    border-top-right-radius: 0px;
    border-bottom-right-radius: 0px;
    background-color: #FF5A51;
    width: 350px;
}
#game {
    border: 2px solid #fff;
    border-radius: 15px;
    background-color: white;
    width: 500px;
    margin: 0 auto;
}
#confirm {
    border: 2px solid #00008B;
    border-radius: 12px;
    border-top-left-radius: 0px;
    border-bottom-left-radius: 0px;
    background-color: #1E90FF;
    width: 142px;
    height: 100px;
}
body {
    background-color: #DFEFF0;
    text-align: center;
}

button {
    font-size: 22px;
    border: 2px solid #87231C;
    border-radius: 100px;
    width: 100px;
    height: 100px;
    color: #FF5A51;
    text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
    padding-top: 36px;
}

button:active {
    font-size: 22px;
    border: 2px solid #328505;
    color: #32A505;
    border-radius: 100px;
    width: 100px;
    height: 100px;
    padding-top: 36px;
}

你可以在这里查看它的外观。 http://jsfiddle.net/VcU7J/

感谢您的帮助!

编辑:我还尝试将浮动元素添加到CSS中,但它更多地搞砸了。 :/

2 个答案:

答案 0 :(得分:2)

有几种方法可以做到这一点。最传统的是使用CSS'float属性你的两个div:

<强> CSS

#choice {
    border: 2px solid #87231C;
    border-radius: 12px;
    border-top-right-radius: 0px;
    border-bottom-right-radius: 0px;
    background-color: #FF5A51;
    width: 350px;

     float:left; 
}
#game {
    border: 2px solid #fff;
    border-radius: 15px;
    background-color: white;
    width: 500px;
    margin: 0 auto;

    /* this is needed to make sure your container background 
      "contains" your floated divs */ 
    overflow:auto; 

}
#confirm {
    border: 2px solid #00008B;
    border-radius: 12px;
    border-top-left-radius: 0px;
    border-bottom-left-radius: 0px;
    background-color: #1E90FF;
    width: 142px;
    height: 100px;

    float:left      
}

fiddle

有关花车的更多信息here

答案 1 :(得分:1)

使用css floats将div放在彼此旁边,但不要忘记在完成后清除浮动。

#game {
    float:left;
}
#confirm {
    float: right;
}
.clear {
    clear: both;
}

然后html看起来像:

<div id="game">
    <div id="choice" onmouseover="npcRoll()">
        <p>Chosse your weapon!</p>
        <button id="rock" onClick="choose(1)">Rock</button>
        <button id="paper" onClick="choose(2)">Paper</button>
        <button id="scissors" onClick="choose(3)">Scissors</button>
        <p>You chose <span id="userChoice">none</span>!</p>
    </div>
    <div id="confirm">    
    </div>
    <div class="clear"></div>
</div>