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
267 views
in Technique[技术] by (71.8m points)

CSS grid - two columns on desktop and 1 column on mobile

This is what I want to achieve:

On desktop/big screen - 30% of the left side and around 70% of the right side

enter image description here

On mobile/smaller screens - right side goes on top of the left side

enter image description here

Here's what I have so far. I have a feeling I'm using the grid in the right or at least I'm not achieving what I have above...

body {
  margin: 40px;
}

.sidebar {
  grid-area: sidebar;
}

.content {
  grid-area: content;
}

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: auto;
  grid-template-areas: "sidebar content content content";
  background-color: #fff;
  color: #444;
}
.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}

.header {
  background-color: #999;
}

@media (max-width: 768px) {
  grid-template-rows: repeat(auto, 1fr);
  grid-template-areas:
    "content"
    "sidebar";
}
<div class="wrapper">
  <div class="box sidebar">Sidebar</div>
  <div class="box content">Content</div>
</div>
question from:https://stackoverflow.com/questions/66045259/css-grid-two-columns-on-desktop-and-1-column-on-mobile

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

1 Reply

0 votes
by (71.8m points)

You forget to wrap css in .wrapper class in media query

body {
  margin: 40px;
}

.sidebar {
  grid-area: sidebar;
}

.content {
  grid-area: content;
}

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: auto;
  grid-template-areas: "sidebar content content content";
  background-color: #fff;
  color: #444;
}
.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}

.header {
  background-color: #999;
}

@media (max-width: 768px) {
  .wrapper {
     grid-template-rows: repeat(auto, 1fr);
      grid-template-areas:
    "content"
    "sidebar";
  }
}
<div class="wrapper">
  <div class="box sidebar">Sidebar</div>
  <div class="box content">Content</div>
</div>

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

...