I want to make a responsive layout with one column on mobile and two columns on desktop.
In very old article on web the author uses javascript, but I guess with modern browsers you can only do this with css.
The best result I've been able to achieve so far is with the following code, but in desktop mode I can't place the sidebar items one behind the other.
I think grid layout is not the right approach.
.container {
display: grid;
grid-template-columns: auto auto;
}
.main {
background-color: blue;
grid-column: 1;
}
.sidebar {
background-color: green;
grid-column: 2;
}
@media screen and (max-width: 600px) {
.container {
grid-template-columns: auto;
}
.main, .sidebar {
grid-column: 1;
}
}
<div >
<div ><span>A1</span></div>
<div ><span>B1</span></div>
<div ><span>A2</span></div>
<div ><span>A3</span></div>
<div ><span>B2</span></div>
<div ><span>C1</span></div>
</div>
Thanks to @vineet-tyagi suggestion I add below the solution which works well for me:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container {
display: grid;
grid-template-columns: auto auto;
grid-auto-flow: dense;
}
.main {
background-color: blue;
grid-column: 1;
}
.sidebar {
background-color: green;
grid-column: 2;
height: fit-content;
}
@media screen and (max-width: 600px) {
.container {
grid-template-columns: auto;
}
.main, .sidebar {
grid-column: 1;
}
}
</style>
</head>
<body>
<div >
<div >
A1
</div>
<div >
B1
</div>
<div >
A2<br>A2<br>A2<br>A2
</div>
<div >
A3
</div>
<div >
B2
</div>
<div >
C1
</div>
</div>
</body>
</html>
CodePudding user response:
Add "grid-auto-flow: dense;" also to the container class.
CodePudding user response:
.container {
display: grid;
grid-template-columns: repeat(1, 1fr);
gap: 10px;
grid-auto-rows: 100px;
}
.container .main,
.container .sidebar {
border: 1px solid black;
}
.container .sidebar {
background:red;
}
@media screen and (min-width: 600px) {
.container {
grid-template-columns: repeat(2, 1fr);
}
.container .sidebar {
grid-column: 2 / 3;
}
.container .sidebar:nth-child(3) {
grid-row: 2 / 1;
background: red;
}
.container .main {
grid-column: 1 / 2;
}
.container .main:nth-last-child(1) {
grid-row: 1 / 1;
}
.container .main:nth-last-child(2) {
grid-row: 2 / 2;
}
}
<div >
<div ><span>sidebar - B2</span></div>
<div ><span>main - A1</span></div>
<div ><span>sidebar - B1</span></div>
<div ><span>main - C1</span></div>
<div ><span>main - A2 </span></div>
<div ><span>main - A3</span></div>
</div>