效果图:
HTML代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CodePen - Layout Templates with CSS Grid</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="./style.css"> </head> <body> <span> <b>1</b> <b>2</b> </span> <span class="template-2col"> <b>1</b> <b>2</b> </span> <span class="template-3col"> <b>1</b> <b>2</b> <b>3</b> </span> <span class="template-4up"> <b>1</b> <b>2</b> <b>3</b> <b>4</b> </span> <span class="template-sidebar--left"> <b>1</b> <b>2</b> <b>3</b> </span> <span class="template-sidebar--right"> <b>1</b> <b>2</b> <b>3</b> </span> </body> </html>
style.css代码:
*{box-sizing: border-box;} span{background: #fff; padding: 1rem; border-radius: 7px; box-shadow: 0 2px 6px -2px rgba(0, 0, 0, 0.42); height: 30vh; display: grid; grid-gap: 0.5rem;} span b{background-color: #7B86F5; border-radius: 4px; display: grid; place-items: center; color: #fff; font-size: 1.5rem;} span.template-2col{grid-template-columns: repeat(2, 1fr);} span.template-3col{grid-template-columns: repeat(3, 1fr);} span.template-4up{grid-template: repeat(2, 1fr)/repeat(2, 1fr);} span.template-sidebar--left{grid-template: "sidebar mainA" "sidebar mainB";} span.template-sidebar--left > :nth-child(1){grid-area: sidebar;} span.template-sidebar--right{grid-template: "mainA sidebar" "mainB sidebar";} span.template-sidebar--right > :nth-child(3){grid-area: sidebar;} body{background: #f9f9f9; min-height: 100vh; display: grid; grid-template-columns: repeat(auto-fit, 30ch); place-content: center; grid-gap: 5vh; max-width: calc((30ch * 3) + (5vh * 2) + 2rem); margin-left: auto; margin-right: auto; padding: 1rem;}