并排对齐两个div [英] Aligning two divs side-by-side
问题描述
我有一个小问题.我正在尝试使用CSS并排对齐两个div,但是,我希望将中心div放置在页面的水平中央,我可以通过以下方式实现:
I have a small problem. I am trying to align two divs side by side using CSS, however, I would like the center div to be positioned horizontally central in the page, I achieved this by using:
#page-wrap { margin 0 auto; }
很好.我想将第二个div放置在中心页面换行的左侧,但是尽管可以确定,但我无法使用浮点数来完成此操作.
That's worked fine. The second div I would like positioned to the left side of the central page wrap but I can't manage to do this using floats although I'm sure it is possible.
我想将红色div推向白色div.
I would like to push the red div up alongside the white div.
这是我当前关于这两个div的CSS,侧边栏是红色div,页面换行是白色div:
Here is my current CSS concerning these two divs, sidebar being the red div and page-wrap being the white div:
#sidebar {
width: 200px;
height: 400px;
background: red;
float: left;
}
#page-wrap {
margin: 0 auto;
width: 600px;
background: #ffffff;
height: 400px;
}
推荐答案
如果包裹了div,就像这样:
If you wrapped your divs, like this:
<div id="main">
<div id="sidebar"></div>
<div id="page-wrap"></div>
</div>
您可以使用以下样式:
#main {
width: 800px;
margin: 0 auto;
}
#sidebar {
width: 200px;
height: 400px;
background: red;
float: left;
}
#page-wrap {
width: 600px;
background: #ffffff;
height: 400px;
margin-left: 200px;
}
虽然外观略有不同,所以我不确定这是您的追求.这会将所有800px
作为一个单元居中放置,而不是将600px
居中放置在左侧的200px
居中位置.基本方法是侧边栏向左浮动,但在主div内部,并且#page-wrap
具有侧边栏的宽度,因为它的左边距将其移动到更远.
This is a slightly different look though, so I'm not sure it's what you're after. This would center all 800px
as a unit, not the 600px
centered with the 200px
on the left side. The basic approach is your sidebar floats left, but inside the main div, and the #page-wrap
has the width of your sidebar as it's left margin to move that far over.
根据评论进行更新:对于这种偏心的外观,您可以执行以下操作:
Update based on comments: For this off-centered look, you can do this:
<div id="page-wrap">
<div id="sidebar"></div>
</div>
使用这种样式:
#sidebar {
position: absolute;
left: -200px;
width: 200px;
height: 400px;
background: red;
}
#page-wrap {
position: relative;
width: 600px;
background: #ffffff;
height: 400px;
margin: 0 auto;
}
这篇关于并排对齐两个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!