CSS布局 - 并排对齐两个div [英] CSS layout - Aligning two divs side by side

查看:433
本文介绍了CSS布局 - 并排对齐两个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题。我试图使用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; }

Thats工作正常。第二个div我想位于中央页包装的左侧,但我不能设法使用浮动,虽然我相信这是可能的。

Thats 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.

也许最好展示我描述的例子:

Maybe its best to show the example of what I am describing:

我想把红色的div推到白色的div旁边。

I would like to push the red div up alongside the white div.

这是我当前关于这两个div的CSS,sidebar是红色div和page-wrap是白色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 为中心,而不是以 200px 600px code>左侧。基本的方法是你的侧边栏浮动左边,但在主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;
}

这篇关于CSS布局 - 并排对齐两个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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