如何在屏幕空间缩小时保持中间的 div 处于顶部?

huangapple go评论53阅读模式
英文:

How do I keep middle div on top when screen estate shrinks?

问题

我有三个div,并希望它们在屏幕允许的情况下排成一行,但如果不行,中间的div应该保持在顶部,左边和右边的div应该移动到它的下方。根据类似Bootstrap的问题的回答(https://stackoverflow.com/questions/38825040/how-to-push-the-middle-div-on-top-in-small-screen-in-bootstrap),看起来可以实现,但我想看到实际的CSS代码。

@media (max-width: your_breakpoint_here) {
  .left, .middle, .right {
    width: 100%;
  }

  .middle {
    order: -1;
  }
}

请将"your_breakpoint_here"替换为你希望中间div在哪个屏幕宽度以下移动到顶部的具体屏幕宽度值。

英文:

I have three divs and I would like them to be laid out in a row when the screen estate permits, but if not, the middle div should stay on top and the left and right should move below it. Given the reply to a similar question about Bootstrap (https://stackoverflow.com/questions/38825040/how-to-push-the-middle-div-on-top-in-small-screen-in-bootstrap) it looks like it is doable, but I would like to see the actual CSS for this.

<div class="left">
LEFT
</div>
<div class="middle">
THIS IS A LONG TEXT
</div>
<div class="right">
RIGHT
</div>

答案1

得分: 1

以下是关于如何使用CSS Grid和媒体查询来实现此效果的实际CSS代码:

.grid {
  display: grid;
  grid-template-areas: "middle" "left" "right";
}

.left {
  grid-area: left;
}

.middle {
  grid-area: middle;
}

.right {
  grid-area: right;
}

@media (min-width:600px) {
  .grid {
    grid-template-areas: "left middle right";
  }
}

如果您想了解有关CSS Grid的更多信息,可以从这里开始:https://css-tricks.com/snippets/css/complete-guide-grid/

英文:

This is the actual CSS on how to do this with CSS Grid and Media Queries.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

.grid {
  display: grid;
  grid-template-areas: &quot;middle&quot; &quot;left&quot; &quot;right&quot;;
}

.left {
  grid-area: left;
}

.middle {
  grid-area: middle;
}

.right {
  grid-area: right;
}

@media (min-width:600px) {
  .grid {
    grid-template-areas: &quot;left middle right&quot;;
  }
}

<!-- language: lang-html -->

&lt;div class=&quot;grid&quot;&gt;
  &lt;div class=&quot;left&quot;&gt;
    LEFT
  &lt;/div&gt;
  &lt;div class=&quot;middle&quot;&gt;
    THIS IS A LONG TEXT
  &lt;/div&gt;
  &lt;div class=&quot;right&quot;&gt;
    RIGHT
  &lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

If you want to learn about CSS Grid, this is a good place to start: https://css-tricks.com/snippets/css/complete-guide-grid/

huangapple
  • 本文由 发表于 2023年5月13日 20:50:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定