我有一个元素,我想要(横轴)居中,但即使内容太少也“增长”到标称大小,但当页面宽度小于 350px 时也会“缩小”。
HTML
<div class="parent">
<div class="child">
Some content
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
社会保障局
.parent {
display: flex;
flex-direction: column;
align-items: center;
.child {
max-width: 350px;
align-self: stretch;
}
}
Run Code Online (Sandbox Code Playgroud)
添加align-self: stretch;到.child可以使其宽度为 350px,但它似乎否定了align-items: center;in.parent
有没有办法在我缺少的 CSS 中做到这一点?请注意,元素不能始终只有 350 像素宽 - 它还必须像示例小提琴中那样响应水平页面调整大小。
Luu*_*ai 7
更新
我认为您应该使用justify-contenth 将孩子对齐到中心。
请注意,当您将display: flex财产应用于父母时,您应该将flex财产应用于孩子。
.parent {
background: yellow;
display: flex;
flex-direction: column;
align-items: center;
}
.parent .child {
background: black;
color: white;
text-align: center;
flex: 1 1 auto;
width: 100%;
max-width: 350px;
}Run Code Online (Sandbox Code Playgroud)
<div class="parent">
<div class="child">
I should be 350px wide
<br> and centered in the yellow
<br> unless the page gets smaller,
<br> in which case I should have
<br> 10px padding on either side.
</div>
</div>Run Code Online (Sandbox Code Playgroud)
请在此处查看结果,希望这就是您的意思:https : //jsfiddle.net/1uqpxn8L/11/