CSS Grid -创建一个单列布局,其中包含居中内容的边距,内容左对齐

olqngx59  于 2023-05-02  发布在  其他
关注(0)|答案(1)|浏览(162)

以下是我正在努力实现的目标:

在移动的设备上,我想要一个居中的单列布局,两边都有边距。列中的内容是一个标签,后跟一个MUI表单字段( Package 在<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>
kgsdhlau

kgsdhlau1#

这比你想象的要容易得多。你不需要网格。只要给予你的 Package 器一个固定的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>

相关问题