Html 如何将侧边栏与主要内容区域的左侧对齐?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4916384/
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-29 06:34:57  来源:igfitidea点击:

How do I align a sidebar to the left of the main content area?

csshtml

提问by MJ93

Hey all, so basically I have a very simple layout with a header image, a main centered text area. And a sidebar that is to the left of the main centered text area. This is basically how my layout looks:

大家好,所以基本上我有一个非常简单的布局,带有标题图像,一个主要的居中文本区域。还有一个位于主要居中文本区域左侧的侧边栏。这基本上是我的布局的外观:

<center>Header</center>
<div style="float:left;">Sidebar</div>
<center>Main Area</center>

Well the sidebar is obviously going to align all the way to the left side of the page, what I would like it to do is still be on the left side of the page, but I want it to "hug" the main centered area.

那么侧边栏显然会一直对齐到页面的左侧,我希望它做的仍然是在页面的左侧,但我希望它“拥抱”主要的居中区域。

Here is a basic picture of what it looks like now, and an arrow of what I would like to happen: http://img18.imageshack.us/img18/2307/exampleps.jpg

这是现在的基本图片,以及我希望发生的事情的箭头:http: //img18.imageshack.us/img18/2307/exampleps.jpg

回答by ?ime Vidas

Live demo:http://jsfiddle.net/rRm7k/

现场演示:http ://jsfiddle.net/rRm7k/

HTML:

HTML:

<div id="wrap">
    <div id="header"> HEADER </div>
    <div id="body">
        <div id="sidebar"> SIDEBAR </div>
        <div id="main"> MAIN CONTENT </div>        
    </div>
</div>

CSS:

CSS:

#wrap { width:500px; margin:0 auto; }
#body { overflow:auto; }
#sidebar { float:left; width:150px; min-height:400px; }

回答by James Love

Try it with all divs instead:

尝试使用所有 div 代替:

<div>Header</div>
<div style="float:left;width:250px">Sidebar</div>
<div style="float:right;">Main Area</div>

回答by gearsdigital

Here is a solution: http://jsfiddle.net/MwEun/1/

这是一个解决方案:http: //jsfiddle.net/MwEun/1/

You have to fit the width of the elements to your needs but should work. This example is a really basic version of an really easy html layout.

您必须根据需要调整元素的宽度,但应该可以。这个例子是一个非常简单的 html 布局的非常基本的版本。

A good and rock solid solution for centering elements is to set a width (e.g. 500px) and then adding margin: 0 auto;

居中元素的一个好的和坚如磐石的解决方案是设置宽度(例如 500px),然后添加 margin: 0 auto;