【问题标题】:Two divs side by side inside wrapper两个 div 在包装器内并排
【发布时间】:2016-10-01 08:40:59
【问题描述】:

我试图将两个 div 并排放置,它们之间有 20px 的边距。 div 位于包装器内部,宽度为 800 像素。左 div 是 250 像素,右 div 是 550 像素,但当然如果我在它们之间添加 20 像素的边距,总宽度会增加超过 800 像素。有没有办法强制右 div 宽度为 550px - 20px 边距?

CSS

.wrapper {
    max-width: 800px;
    height: 400px;
    background-color: green;
    margin: 0 auto;
}

.left {
    width: 250px;
    height: 300px;
    background-color: blue;
    float: left;
    margin-right: 20px;
}

.right {
    width: 550px;
    height: 300px;
    background-color: red;
    float: left;
}

HTML

<body>
    <div class="wrapper">
        <div class="left">
        </div>

        <div class="right">
        </div>
    </div>
</body>

我的意思是我必须手动减小宽度还是有更好的解决方案?

jsfiddle:https://jsfiddle.net/ytsvd77f/

【问题讨论】:

  • 请将您的代码添加到 jsfiddle 并发送链接以获得更有效的答案。
  • 为简单起见响应您的代码.. add display: flex;在你的包装中。让我知道它是否有效
  • 是否有理由不只是将宽度设为 530 像素?我是唯一一个会在脑海中做数学的人吗?

标签: html css


【解决方案1】:

是的,您可以使用 calc(550px - 20px) 作为右 div 的 width

.wrapper {
  max-width: 800px;
  height: 400px;
  background-color: green;
  margin: 0 auto;
}
.left {
  width: 250px;
  height: 300px;
  background-color: blue;
  float: left;
  margin-right: 20px;
}
.right {
  width: -moz-calc(550px - 20px);
  width: -webkit-calc(550px - 20px);
  width: -o-calc(550px - 20px);
  width: calc(550px - 20px);
  height: 300px;
  background-color: red;
  float: left;
}
<div class="wrapper">
  <div class="left"></div>
  <div class="right"></div>
</div>

【讨论】:

  • 谢谢!我不知道calc!这是最佳做法吗?
  • 我会选择这个,你也可以用填充做这样的jsfiddle.net/Lg0wyt9u/929
  • 为什么要将calc()与相同单位的静态值一起使用,而不仅仅是530px
  • 计算在这里没有意义
【解决方案2】:

如果您在包装器中添加 display:flex,它将完美运行,我想您会更好地理解。 检查一下css。

    .wrapper {
       max-width: 800px;
       height: 400px;
       background-color: green;
       margin: 0 auto;
       display: flex;
    }

【讨论】:

    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    相关资源
    最近更新 更多