我需要将一组孩子放在容器的中央。
我的要求是:
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>
有什么方法可以可靠地实现我的追求吗?
答案 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
的样式规则。