Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
953 views
in Technique[技术] by (71.8m points)

flexbox - Different alignment of elements in CSS Grid or Flex after a line break

I suggest running the code snippet below to better understand this question, as it is a layout question, and visually easier to understand.

I have an element on my page that needs to display one item (a Title) aligned to the left, and another item (Date/Time) aligned to the right, in the same "row". I accomplished this easily using CSS Grid.

My designer told me that when we display on a mobile device, it should instead show the Title left-aligned, and the Date/Time below that on the next line, ALSO left-aligned. CSS Flex does this with grace.

Is there a way to make either CSS Grid or CSS Flex do both of these things, without jumping through hoops?

What I'm trying to avoid is having to write a slew of @media breakpoints, and just handle it organically instead, if possible.

Thanks for any advice you can offer.

.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? 
question from:https://stackoverflow.com/questions/65911833/different-alignment-of-elements-in-css-grid-or-flex-after-a-line-break

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Flexbox is really all you need.

.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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...