【问题标题】:How can I apply margins so that elements don't exceed 100% width?如何应用边距以使元素不超过 100% 宽度?
【发布时间】:2018-10-25 13:00:04
【问题描述】:

我有 this layout,我希望能够在每个元素周围添加 margin,但不更改每个元素的 宽度 .

我知道,例如使用header,我可以应用margin: 10px;(让我们关注左右边距)和width: calc(100% - 20px),它从100% 中减去20px边距。

问题
有没有办法在不改变宽度的情况下做到这一点?

所以我可以保持 100% 的宽度,而不必担心我对元素应用了多少边距?

【问题讨论】:

  • 边距和宽度/高度就像油和水。他们不融合。所以你的问题的答案是“不”。但是,如果您对其他间距选项持开放态度,那么有很多。这是一个开始:stackoverflow.com/q/45057867/3597276
  • 您可以使用边框代替box-sizing: border-box。或内部轮廓或插入框阴影
  • 在您的情况下,您无法在不更改宽度的情况下做到这一点,但您可以通过删除宽度来做到这一点。考虑到边距,Divs 将适合可用空间。
  • @rpm192 你读过这个问题吗?如果您查看我的示例,您会看到我已经在使用 Flexbox。我解释说我也不想更改每个元素宽度的百分比。

标签: html css flexbox width margin


【解决方案1】:

你可以和flex-grow一起玩。在您的情况下,您以这种方式定义了宽度:20% + 60% + 20%,即20% + 3*20% + 20%,所以我们有类似1 + 3 + 1 的因素。因此,使用这些因素设置flex-grow,然后您可以轻松添加所需的边距。

* {
  box-sizing: border-box;
}

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

body {
  background: #333D4E;
}


/* Main */

main {
  display: flex;
  flex-direction: row;
  width: 100%;
  text-align: center;
}

article {
  flex-grow: 3;
  min-height: 800px;
  background: #EDF0F1;
  border-radius: 5px;
  margin: 0 20px;
}

nav {
  flex-grow: 1;
  order: -1;
  min-height: 800px;
  background: #9AA4A6;
  border-radius: 5px;
}

aside {
  flex-grow: 1;
  order: 1;
  min-height: 800px;
  background: #6295D6;
  border-radius: 5px;
}
<main>
  <article>Main Content</article>
  <nav>Side Nav</nav>
  <aside>Aside</aside>
</main>

同样适用于单个元素:

body {
  margin:0;
  display:flex;
}

.container {
  min-height:200px;
  flex-grow:1;
  margin:0 25px;
  background:red;
}
<div class="container">

</div>

所以诀窍是找到要使用的正确flex-grow 值。

【讨论】:

    猜你喜欢
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多