css - 如何使用 CSS 将按钮移动到新行?

标签 css reactjs material-ui

我正在使用 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: leftdisplay: 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/

相关文章:

html - 制作带有标签和输入的移动页面的简单方法

jquery - 在鼠标悬停时显示 PNG 的不同部分

html - css3 -moz-border-image 不工作?

javascript - 无法读取数组长度

javascript - React-Redux 与 Formik 连接 - 超出最大调用堆栈大小

javascript - React 无法识别 DOM 元素上的 `justifyContent` 属性

css - 如何使用 MUI v5 主题创建自定义 CSS 类?

html - 取决于文本行的自动 css 样式

reactjs - 是的。当 : "` NaN` (cast from the value `NaN` )"

javascript - 无法将material-ui GridList居中