【问题标题】:Different alignment of elements in CSS Grid or Flex after a line break换行后 CSS Grid 或 Flex 中元素的不同对齐方式
【发布时间】:2021-01-27 09:58:19
【问题描述】:

我建议运行下面的代码 sn-p 以更好地理解这个问题,因为它是一个布局问题,并且在视觉上更容易理解。

我的页面上有一个元素需要在同一“行”中显示一个左对齐的项目(标题)和右对齐的另一个项目(日期/时间)。我使用 CSS Grid 轻松完成了这项工作。

我的设计师告诉我,当我们在移动设备上显示时,它应该显示标题左对齐,而日期/时间在下一行显示,也左对齐。 CSS Flex 优雅地做到了这一点。

有没有一种方法可以让 CSS Grid 或 CSS Flex 完成这两项工作,而无需费劲?

我试图避免的是必须编写大量的@media 断点,并尽可能有机地处理它。

感谢您提供的任何建议。

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  font-weight: bold;
}

.date {
  justify-self: end;
}

.flex-container {
  display: flex;
  flex-direction: column;
  font-weight: bold;
}
When on a wide device screen (e.g. Desktop Web Browser) I want the layout to look like this. The title should be on the left and left aligned, the date/time should be on the right and right aligned. The should adjust with the page width.
<p>
  <div class="container">
    <div>Some Title</div>
    <div class="date">01/26/2021 10:30am</div>
  </div>
</p>

However, when on a small device screen (e.g. smart phone) the Title should appear on one line, left aligned, and the Date/Time should appear below it, also left aligned.
<p>
  <div class="flex-container">
    <div>Some Title</div>
    <div class="date">01/26/2021 10:30am</div>
  </div>
</p>

Is there a way to accomplish this easily, hopefully using CSS Grid or Flex, rather than hard coding CSS changed to breakpoints? 

【问题讨论】:

    标签: css flexbox css-grid


    【解决方案1】:

    Flexbox 真的是你所需要的。

    .container {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
    }
    <div class="container">
      <div>Some Title</div>
      <div class="date">01/26/2021 10:30am</div>
    </div>

    【讨论】:

    • 谢谢迈克尔,这确实使 Flex 可以正确处理单行,但是当我在小型设备上查看它时,它永远不会变成 2 行,并且不会左对齐两行。这就是我想要实现的目标。
    • 当屏幕足够小时它会自动换行并左对齐 (test here)。你想把它包在哪里?
    • 在标题之后。如果您运行我发布的代码 sn-p,它会准确显示它在宽屏幕上的外观,以及在小屏幕上的外观。我尝试使用 iPhone X 配置文件(它通常是最薄的设备)在模拟器中运行它,并且它从未“中断”到新行。也许我只需要在元素上设置更宽的宽度?嗯....
    • 好吧,我知道您正试图避免媒体查询,但这项工作正是他们的设计目的。如果没有媒体查询,文本将根据其内容换行。它无法知道其他任何事情。
    • @ToddDavis 在标题中添加一些 padding-right 或 margin-right 以便更快地完成包装
    猜你喜欢
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多