如何水平放置html中的三个div?

新手上路,请多包涵

我正在创建一个横向分为三个部分的示例网站。我希望最左边的 div 宽度为 25%,中间的 div 宽度为 50%,右边的宽度为 25%,以便这些分区水平填充所有 100% 的空间。

 <html>
    <title>
    Website Title
    </title>

    <div id="the whole thing" style="height:100%; width:100%" >

        <div id="leftThing" style="position: relative; width:25%; background-color:blue;">
            Left Side Menu
        </div>

        <div id="content" style="position: relative; width:50%; background-color:green;">
            Random Content
        </div>

        <div id="rightThing" style="position: relative; width:25%; background-color:yellow;">
            Right Side Menu
        </div>

    </div>
</html>

http://imgur.com/j4cJu

当我执行这段代码时,div 出现在彼此之上。我要他们出现在彼此的身边!

我怎样才能做到这一点?

原文由 Akhil 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

我不会在这种事情上使用花车;我宁愿使用 inline-block

还有一些要考虑的要点:

  • 内联样式不利于可维护性
  • 你不应该在选择器名称中有空格
  • 你错过了一些重要的 HTML 标签,比如 <head><body>
  • 您没有包含 doctype

这是格式化文档的更好方法:

 <!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<style type="text/css">
* {margin: 0; padding: 0;}
#container {height: 100%; width:100%; font-size: 0;}
#left, #middle, #right {display: inline-block; *display: inline; zoom: 1; vertical-align: top; font-size: 12px;}
#left {width: 25%; background: blue;}
#middle {width: 50%; background: green;}
#right {width: 25%; background: yellow;}
</style>
</head>
<body>
<div id="container">
    <div id="left">Left Side Menu</div>
    <div id="middle">Random Content</div>
    <div id="right">Right Side Menu</div>
</div>
</body>
</html>

这是一个很好的衡量标准的 jsFiddle

原文由 Jezen Thomas 发布,翻译遵循 CC BY-SA 3.0 许可协议

我知道这是一个非常古老的问题。当我使用 FlexBox 解决这个问题时,就把它贴在这里。这是解决方案

 #container {
  height: 100%;
  width: 100%;
  display: flex;
}
#leftThing {
  width: 25%;
  background-color: blue;
}
#content {
  width: 50%;
  background-color: green;
}
#rightThing {
  width: 25%;
  background-color: yellow;
}
 <div id="container">

  <div id="leftThing">
    Left Side Menu
  </div>

  <div id="content">
    Random Content
  </div>

  <div id="rightThing">
    Right Side Menu
  </div>

</div>

只需将 display:flex 添加到容器中!不需要花车。

原文由 maazadeeb 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题