使用最大宽度和不使用边距将内容居中

时间:2019-09-16 17:43:08

标签: css layout flexbox constraints

我需要将一组孩子放在容器的中央。

我的要求是:

  1. 每个孩子的左右两侧都需要一个排水沟。
  2. 我无法在容器上设置边距或填充。
  3. 我不能在孩子身上设置填充,但是我可以设置边距。
  4. 每个孩子的左右两侧都应有一个空格/排水沟。
  5. 每个孩子可以设置不同的最大宽度。
  6. 如果孩子的最大宽度大于容器的宽度,则它应占据整个宽度(减去其装订线)。
  7. 如果孩子比容器窄,则应居中。 我以为我可以用flexbox做到这一点,因为align-items: stretch;尊重max-widths,但是它不会使孩子们居中。

我不能使用margin: 0 auto;,因为我需要利用孩子们的边缘在左右两侧设置装订线。

这是我尝试使用flexbox:

* {
  box-sizing: border-box;
}

main {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  text-align: center;
  max-width: 600px;
  outline: 1px dashed black;
  box-
}

section {
  min-height: 40px;
  margin-left: 20px;
  margin-right: 20px;
}

section + section {
  margin-top: 20px;
}
  
.s1 {
  background-color: red;
  max-width: 100px
}
  
.s2 {
  background-color: blue;
  max-width: 200px
}
  
.s3 {
  background-color: green;
  max-width: 300px
}
<main>
  <section class='s1'></section>
  <section class='s2'></section>
  <section class='s3'></section>
</main>

有什么方法可以可靠地实现我的追求吗?

2 个答案:

答案 0 :(得分:2)

是的,尽管您需要给section设置宽度,然后使用align-items: center

要在孩子达到其父母的宽度时保持排水沟,可以使用CSS calc(),例如width: calc(100% - 40px);,并且由于较窄的孩子始终居中,因此您也应该可以放下margin-left/right(如果可以,则可以使用自动边距)。

请注意,如果不使用safe关键字,则使用align-items: center can cause overflow issues,并使用自动边距可以解决跨浏览器比safe多的问题。

堆栈片段

* {
  box-sizing: border-box;
}

main {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  max-width: 600px;
  outline: 1px dashed black;
}

section {
  width: calc(100% - 40px);
  min-height: 40px;
  margin-left: 20px;
  margin-right: 20px;
}

section + section {
  margin-top: 20px;
}
  
.s1 {
  background-color: red;
  max-width: 100px
}
  
.s2 {
  background-color: blue;
  max-width: 200px
}
  
.s3 {
  background-color: green;
  max-width: 700px
}
<main>
  <section class='s1'></section>
  <section class='s2'></section>
  <section class='s3'></section>
</main>


如果您能够删除固定边距,请按照以下方法使用自动边距

堆栈片段

* {
  box-sizing: border-box;
}

main {
  display: flex;
  flex-direction: column;
  text-align: center;
  max-width: 600px;
  outline: 1px dashed black;
}

section {
  width: calc(100% - 40px);
  min-height: 40px;
  margin: 0 auto;
}

section + section {
  margin-top: 20px;
}
  
.s1 {
  background-color: red;
  max-width: 100px
}
  
.s2 {
  background-color: blue;
  max-width: 200px
}
  
.s3 {
  background-color: green;
  max-width: 700px
}
<main>
  <section class='s1'></section>
  <section class='s2'></section>
  <section class='s3'></section>
</main>

答案 1 :(得分:0)

如果用max-width替换孩子中的width,则可以实现您想要的目标。但是我不知道进行此更改是否有任何限制。

将这些规则添加到所有部分

section {
  max-width: calc(100% - 40px);
  margin: 0 auto;
}

如果将max-width中的.s1, .s2 and .s3替换为width,则可以完全省略main的样式规则。

相关问题