如何将两个div并排放置? [英] How to place two divs next to each other?

查看:56
本文介绍了如何将两个div并排放置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

#wrapper {宽度:500px;边框:1px纯黑色;}#第一的 {宽度:300px;边框:1px纯红色;}#第二 {边框:1px纯绿色;}

<div id="first">Stack Overflow 适合专业和狂热的程序员,他们编写代码是因为他们喜欢它.</div><div id="second">当您发布新问题时,其他用户几乎会立即看到它并尝试提供好的答案.这通常会在几分钟内发生,因此当您的问题仍然是新问题时,请务必经常回来查看以获得最佳答复.</div>

我希望两个 div 在包装 div 内彼此相邻.在这种情况下,绿色 div 的高度应该决定包装器的高度.

我如何通过 CSS 实现这一点?

解决方案

浮动一个或两个内部 div.

浮动一个div:

#wrapper {宽度:500px;边框:1px纯黑色;溢出:隐藏;/* 将包含如果#first 长于#second */}#第一的 {宽度:300px;向左飘浮;/* 添加这个 */边框:1px纯红色;}#第二 {边框:1px纯绿色;溢出:隐藏;/* 如果你不想 #second 包裹在 #first 下面 */}

或者如果你同时浮动,你需要鼓励包装器 div 包含浮动的孩子,否则它会认为它是空的,而不是在它们周围放置边框

浮动两个 div:

#wrapper {宽度:500px;边框:1px纯黑色;溢出:隐藏;/* 添加这个以包含浮动的孩子 */}#第一的 {宽度:300px;向左飘浮;/* 添加这个 */边框:1px纯红色;}#第二 {边框:1px纯绿色;向左飘浮;/* 添加这个 */}

Consider the following code:

#wrapper {
    width: 500px;
    border: 1px solid black;
}
#first {
    width: 300px;
    border: 1px solid red;
}
#second {
    border: 1px solid green;
}

<div id="wrapper">
    <div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>
    <div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>
</div>

I would like the two divs to be next to each other inside the wrapper div. In this case, the height of the green div should determine the height of the wrapper.

How could I achieve this via CSS ?

解决方案

Float one or both inner divs.

Floating one div:

#wrapper {
    width: 500px;
    border: 1px solid black;
    overflow: hidden; /* will contain if #first is longer than #second */
}
#first {
    width: 300px;
    float:left; /* add this */
    border: 1px solid red;
}
#second {
    border: 1px solid green;
    overflow: hidden; /* if you don't want #second to wrap below #first */
}

or if you float both, you'll need to encourage the wrapper div to contain both the floated children, or it will think it's empty and not put the border around them

Floating both divs:

#wrapper {
    width: 500px;
    border: 1px solid black;
    overflow: hidden; /* add this to contain floated children */
}
#first {
    width: 300px;
    float:left; /* add this */
    border: 1px solid red;
}
#second {
    border: 1px solid green;
    float: left; /* add this */
}

这篇关于如何将两个div并排放置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆