Html 并排对齐 2 个 Div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9683254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:05:08  来源:igfitidea点击:

Align 2 Divs side by side

csshtmlcss-float

提问by Vetaxili

I've never had a problem with aligning divs side by side but for some reason no matter what I do it just doesn't work. I tried a few answers from stackoverflow but they didn't work either. I've run out of ideas.

我从来没有遇到并排对齐 div 的问题,但出于某种原因,无论我做什么,它都不起作用。我从 stackoverflow 尝试了一些答案,但它们也不起作用。我已经没有想法了。

What I have are 2 divs. 1 div is "content" - it has all main info displayed in a table. Second div is "sidebar" - it has just some extra rubbish like images, twitter feed etc.

我拥有的是 2 个 div。1 div 是“内容” - 它在表格中显示了所有主要信息。第二个 div 是“侧边栏” - 它只有一些额外的垃圾,如图像、推特提要等。

This is my CSS

这是我的 CSS

#content {
width: 580px;
height:auto;
}     

#sidebar {
width: 270px;
height:auto;
float:right;

}

}

I've tried to play with positioning, margins, containing those 2 divs in another - wrapper - one but it either doesn't work or creates another problem. Funny enough I am re-writing my old website and even if I copy the old attributes it still doesn't work. Anyone has any idea?

我尝试在另一个包装器中使用定位、边距、包含这 2 个 div - 一个包装器 - 但它要么不起作用,要么产生另一个问题。有趣的是,我正在重新编写我的旧网站,即使我复制了旧属性,它仍然无法正常工作。任何人有任何想法?

EVERYONE IS ALLOWED TO LAUGHT! LOL

每个人都可以大笑!哈哈

SOLUTION: Delete div #clear which I totally forgot about! What a muppet. :-P Now I feel stupid. :-P

解决方案:删除我完全忘记的 div #clear !什么布偶。:-P 现在我觉得自己很愚蠢。:-P

回答by Zoltan Toth

#content {
  background:#eee;
  width: 300px;
  height:auto;
  float: left;
}     

#sidebar {
  background:#c00;
  width: 200px;
  height:auto;
  float:left;
}
<div id="content">Content</div>
<div id="sidebar">Sidebar</div>

回答by Ashwin Krishnamurthy

Use float : left, here is a simple example illustrating the usage of floats.

使用float : left,这里有一个简单的例子来说明浮点数的用法。

DEMO

演示

Taking your case into account, this css oughta do the trick

考虑到您的情况,这个 css 应该可以解决问题

#content {
    float : left;
    width: 580px;
    height:auto;
}     
#sidebar {
    float : left;
    width: 270px;
    height:auto;
    float:right;

}

Provided you have a container with a width greater than the sum of the widths of the #sidebarand the #contentelements. If the container width is lesser, one will appear below the other as shown in the demo.

假设您有一个宽度大于#sidebar#content元素宽度总和的容器。如果容器宽度较小,则一个将出现在另一个下方,如演示中所示。

回答by Zuazua

To answer in a proper way, I need to see more than just two CSS id's, like the HTML page and the CSS file, but I did this:

为了以正确的方式回答,我需要看到的不仅仅是两个 CSS id,比如 HTML 页面和 CSS 文件,但我这样做了:

JSFiddle

JSFiddle

And maybe could help you.

也许可以帮助你。