【问题标题】:Width percentage with margin and different nestings带边距和不同嵌套的宽度百分比
【发布时间】:2018-11-10 16:59:31
【问题描述】:

在我的网页中,我有一个左右部分,但它们不在同一个嵌套中。我希望左侧部分填充页面的 25%,右侧部分填充其余宽度。
简单地设置 75% 对我来说并不合适,因为右边的部分也需要 30px 的右边margin。正确的 padding 不起作用,因为我的内容和 background-color 会溢出。
你知道如何解决这个问题吗?
.left(蓝色)和.right(黄色)div 应该总是完美地相遇,.right 需要保持 30px 正确margin

body {
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  bottom: 0;
  overflow: hidden;
}

.main {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  overflow: hidden;
  background-color: grey;
}

.left {
  position: absolute;
  top: 0;
  bottom: 0;
  padding-top: 0;
  padding-bottom: 0;
  left: 0;
  width: 25%;
  border-right: 1px solid #eeeeee;
  background-color: lightblue;
}

.right {
  position: absolute;
  width: 75%;
  right: 0px;
  top: 45px;
  bottom: 0;
  /*padding-right: 30px;*/
  margin-right: 30px;
  background-color: yellow;
}
<body>
  <div class="main">
    <div class="left">TEST</div>
  </div>
  <div class="right">TEST</div>
</body>

【问题讨论】:

    标签: html css width margin


    【解决方案1】:

    仅使用绝对位置创建布局不是一个好主意。例如,您可能会更好地依赖 flexbox:

    body {
      height: 100vh;
      margin: 0;
      display: flex;
      background: grey;
    }
    
    .left {
      flex: 1;
      border-right: 1px solid #eeeeee;
      background-color: lightblue;
    }
    
    .right {
      flex: 4;
      margin-top: 45px;
      margin-right: 30px;
      background-color: yellow;
    }
    <div class="left">TEST</div>
    <div class="right">TEST</div>

    但如果你想保留你的代码,你需要在计算宽度时考虑边距:

    body {
      display: block;
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      bottom: 0;
      overflow: hidden;
    }
    
    .main {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
      overflow: hidden;
      background-color: grey;
    }
    
    .left {
      position: absolute;
      top: 0;
      bottom: 0;
      padding-top: 0;
      padding-bottom: 0;
      left: 0;
      width: 25%;
      border-right: 1px solid #eeeeee;
      background-color: lightblue;
    }
    
    .right {
      position: absolute;
      width: calc(75% - 30px);
      right: 0px;
      top: 45px;
      bottom: 0;
      /*padding-right: 30px;*/
      margin-right: 30px;
      background-color: yellow;
    }
    <body>
      <div class="main">
        <div class="left">TEST</div>
      </div>
      <div class="right">TEST</div>
    </body>

    【讨论】:

    • 谢谢,我不知道那个 calc(75% - 30px) 方法——这很有帮助:)
    猜你喜欢
    • 2015-08-12
    • 1970-01-01
    • 2020-04-03
    • 2012-02-15
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多