【问题标题】:How to position divs correctly如何正确定位div
【发布时间】:2022-01-07 07:33:15
【问题描述】:

我有 3 个 div,主、右和左。主 div 包含左右 div,我想并排对齐左右 div。我在这里阅读了几篇文章,但未能获得预期的结果。

https://jsbin.com/lagikaxiwe/edit?html,css,output

html,
body {
  margin: 0;
  padding: 0;
}

div#main-content {
  background-color: bisque;
  height: 100%;
}

div#right-content {
  position: relative;
  width: 35%;
  height: 100%;
  background-color: #ffffff;
}

div#left-content {
  position: absolute;
  width: calc(100% - 35%);
  height: 100%;
  margin: 0px 0px 0px 666px;
  background-color: #00aeef;
}
<div id="main-content">
  <div id="right-content">
  </div>
  <div id="left-content">
  </div>
</div>

【问题讨论】:

  • 绝对定位是一种非常糟糕的网页布局方法。它非常不灵活,并且有更好和响应速度更快的选项。查看LearnLayout.com
  • @Paulie_D,谢谢你的链接。还在学习 CSS,所以坚持旧观念。
  • 我没有把代码放在sn-p中,因为它没有显示整个东西。
  • 那么您需要编辑您的问题并包含minimal reproducible example,否则您的问题将被关闭。

标签: css css-position


【解决方案1】:

当今最简单的在容器上使用display: flex 的方法。看看我的 sn-p 中的设置 - 我删除了很多其他设置,这些设置是不必要的......

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

div#main-content {
  background-color: bisque;
  height: 100%;
  display: flex;
}

div#right-content {
  width: 35%;
  height: 100%;
  background-color: red;
}

div#left-content {
  width: 65%;
  height: 100%;
  background-color: #00aeef;
}
<div id="main-content">
  <div id="right-content">
  </div>
  <div id="left-content">
  </div>
</div>

【讨论】:

  • flex 与 IE 兼容吗?我必须确保它适用于所有浏览器。
  • 取决于版本 - 从 11 开始,是的。见caniuse.com/#search=flexbox
【解决方案2】:
html,
body {
  margin: 0;
  padding: 0;
}

div#main-content {
      background-color: bisque;
      height: 100%;
      width: 100%;
}

div#right-content {
  float: left;
  width: 35%;
  height: 100%;
  background-color: #ffffff;
}

div#left-content {
  width: calc(100% - 35%);
  height: 100%;
  background-color: #00aeef;
  float: left;
}

【讨论】:

    【解决方案3】:

    我个人会使用display:inline-block 来对齐左右 div 并排并添加必要的宽度以添加到父宽度的 100%。请务必在父级上使用font-size:0 以消除左右 div 之间的空白,以便它们正确地彼此相邻。

    确保为您的左右内容分配字体大小,以便您的内容真正显示出来!

    此方法在很大程度上向后兼容所有浏览器。

    div#main-content{
        font-size:0;
    }
    
    div#left-content{
        display:inline-block;
        vertical-align:top;
        width:65%;
    }
    
    div#right-content{
        display:inline-block;
        vertical-align:top;
        width:35%;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      相关资源
      最近更新 更多