这是我想要实现的目标的图片:
在移动设备上,我想要一个居中的单列布局,两边都有边距。列中的内容是一个标签,后跟一个 MUI 表单字段(用
<span>
包裹)。我希望标签及其下方的内容彼此左对齐。
我知道组件的确切宽度,如果标签很长,我希望它环绕起来。
最后,这里的行数是动态的,所以我不知道到底有多少行可以使用
grid-template-areas
。我创建了一个网格布局,但我似乎无法将任何内容布局到列中,更不用说我想要实现的其他事情了。
任何帮助将不胜感激。
.wrapper {
display: grid;
grid-template-columns: 1fr 300px 1fr;
grid-auto-flow: row;
grid-template-areas: 'side content side';
}
.field {
grid-area: content;
border: 1px solid gray;
padding: 10px;
}
.label {
hyphens: auto; /* not sure which of these to use to wrap the longer labels */
word-break: break-all;
overflow-wrap: break-word;
}
.other-data {
display: block; /* this is controlled by an external MUI style so can't be changed */
}
<div class="wrapper">
<div class="field">
<span class="label">Label 1</span>
<span class="other-data">Some other stuff 1</span>
</div>
<div class="field">
<span class="label">Label 2</span>
<span class="other-data">Some other stuff 2</span>
</div>
<div class="field">
<!-- Try with a long label -->
<span class="label">Label 3 - Longer label</span>
<span class="other-data">Some other stuff 3</span>
</div>
<div class="field">
<span class="label">Label 4</span>
<span class="other-data">Some other stuff 4</span>
</div>
</div>
这比你想象的要容易得多。你不需要网格。只需给你的包装纸一个固定的
width: 300px;
然后用margin-left: auto; margin-right: auto;
居中。
.wrapper {
width: 300px;
margin-left: auto;
margin-right: auto;
}
.field {
border: 1px solid gray;
padding: 10px;
}
.other-data {
display: block; /* this is controlled by an external MUI style so can't be changed */
color: red;
}
<div class="wrapper">
<div class="field">
<span class="label">Label 1</span>
<span class="other-data">Some other stuff 1</span>
</div>
<div class="field">
<span class="label">Label 2</span>
<span class="other-data">Some other stuff 2</span>
</div>
<div class="field">
<!-- Try with a long label -->
<span class="label">Label 3 - A really long label should wrap like this a really long label should wrap like this a really long label should wrap like this</span>
<span class="other-data">Some other stuff 3</span>
</div>
<div class="field">
<span class="label">Label 4</span>
<span class="other-data">Some other stuff 4</span>
</div>
</div>