居中最大宽度与 display:flex 不一致
centered max-width doesn't fluid with display:flex
要将 display: block
人的项目居中,请使用 margins: auto
。如果我将 max-width
设置为需要居中的子项,并且周围有足够的 space,它将根据需要(取决于其内容)流动到 max-width
。但是,如果我将父元素的 display
属性 更改为 flex
,它就不再需要全部免费 space。我真的需要使用 max-width
,因为我希望元素在小屏幕上缩小。
这是 jsfiddle 。单击按钮会将父项上的 display: flex
交换为 display: block
。我希望 flex
上的绿色 space 在 max-width
上尽可能流畅,就像在 display:block
上一样
编辑:
我也想用 flex-direction: column
$('input').click(function() {
var curDisplay = $('#parent').css('display');
if (curDisplay == 'block') {
$('#parent').css('display', 'flex');
$('input').val('flex');
} else {
$('#parent').css('display', 'block');
$('input').val('block');
}
})
#parent {
display: flex;
flex-direction: column;
width: 100%;
background-color: red;
height: 50px;
}
#child {
max-width: 300px;
background-color: green;
height: 50px;
margin: auto;
}
input {
width: 100%:
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div id="child">
<input type="button" value="Click Me!" />
</div>
</div>
我认为您正在寻找 flex-basis。通过使用 %,您可以非常接近。您可以使用 px 设置初始宽度,如果您设置了它,它仍然是 "responsive" 直到您达到最小宽度。
关于子元素:
div {
flex-basis:40%;
}
这里是W3
为什么不直接将 child 的宽度设置为 100%?如果您需要将按钮居中放置在 child 中,您只需添加:
display: flex;
justify-content: center;
同时从输入中删除 width: 100%
。
要将 display: block
人的项目居中,请使用 margins: auto
。如果我将 max-width
设置为需要居中的子项,并且周围有足够的 space,它将根据需要(取决于其内容)流动到 max-width
。但是,如果我将父元素的 display
属性 更改为 flex
,它就不再需要全部免费 space。我真的需要使用 max-width
,因为我希望元素在小屏幕上缩小。
这是 jsfiddle 。单击按钮会将父项上的 display: flex
交换为 display: block
。我希望 flex
上的绿色 space 在 max-width
上尽可能流畅,就像在 display:block
编辑:
我也想用 flex-direction: column
$('input').click(function() {
var curDisplay = $('#parent').css('display');
if (curDisplay == 'block') {
$('#parent').css('display', 'flex');
$('input').val('flex');
} else {
$('#parent').css('display', 'block');
$('input').val('block');
}
})
#parent {
display: flex;
flex-direction: column;
width: 100%;
background-color: red;
height: 50px;
}
#child {
max-width: 300px;
background-color: green;
height: 50px;
margin: auto;
}
input {
width: 100%:
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div id="child">
<input type="button" value="Click Me!" />
</div>
</div>
我认为您正在寻找 flex-basis。通过使用 %,您可以非常接近。您可以使用 px 设置初始宽度,如果您设置了它,它仍然是 "responsive" 直到您达到最小宽度。
关于子元素:
div {
flex-basis:40%;
}
这里是W3
为什么不直接将 child 的宽度设置为 100%?如果您需要将按钮居中放置在 child 中,您只需添加:
display: flex;
justify-content: center;
同时从输入中删除 width: 100%
。