我正在使用 React 和 Material-UI,并创建了一个小键盘。我有一个看起来像这样的代码段(其中 KeyPadButton
是来自 Material-UI 的 RaisedButton
):
// partially removed for brevity
const keys = [7, 8, 9, 4, 5, 6, 1, 2, 3, 0];
return (
<div>
{keys.map(key => {
return (
<KeyPadButton key={`button-${key}`}
value={key}
styles={[4, 1, 0].includes(key) ? styles.keypadButtonStyles : {}}
/>
)
})}
</div>
);
const styles = {
keypadButtonStyles: {
clear: 'left',
display: 'table',
},
}
所以,基本上,我希望数字显示为:
7、8、9
4, 5, 6
1, 2, 3
0
因此,我希望数字 4, 1, 0
位于新行中。我尝试应用 clear: left
和 display: table
但它会将它们移动到一个新行中,但它们单独在一行中,而我想要例如 5 , 6
紧挨着 4
等。我不能使用 display: block
因为它破坏了 Material-UI 的一些默认样式。有什么想法可以实现我想要的吗?
最佳答案
带有 flex-wrap: wrap;
的 Flexbox 应该可以与任何子元素一起使用,包括 RaisedButton
。
工作片段(使用简化的 JS,重要部分是 CSS):
const keys = [7, 8, 9, 4, 5, 6, 1, 2, 3, 0];
htmlKeys = keys.map(key => `<div class=key>${key}</div>`);
document.querySelector(".keypad").innerHTML = htmlKeys.join("");
.keypad {
width: 12em;
display: flex;
flex-wrap: wrap;
background: #333;
}
.key {
width: 3em;
background: #444;
color: #eee;
text-align: center;
line-height: 3em;
border-radius: 0.25em;
margin: 0.25em;
}
<div class=keypad />
使用 display: inline-block
的替代“老派”解决方案(可能与 Material UI 中的某些样式冲突):
const keys = [7, 8, 9, 4, 5, 6, 1, 2, 3, 0];
htmlKeys = keys.map(key => `<div class=key>${key}</div>`);
document.querySelector(".keypad").innerHTML = htmlKeys.join("");
.keypad {
width: 12em;
background: #333;
}
.key {
width: 3em;
background: #444;
color: #eee;
text-align: center;
line-height: 3em;
border-radius: 0.25em;
margin: 0.25em;
display: inline-block;
}
<div class=keypad />
另一种可能性是 CSS grid , 但我认为 flexbox 在这种情况下就足够了(并且有更好的浏览器支持)。
关于css - 如何使用 CSS 将按钮移动到新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49383204/