繁体   English   中英

具有跨度的响应式 css 网格

[英]Responsive css grid with span

我正在尝试创建响应式 css 网格,我在其中设置了一些 div 以占用不同的空间,但是当我调整大小时,它们应该每行对齐一个。 这就是它当前的行为方式,除了我设置为具有grid-column: span 2那些元素在它们的右侧留下空白空间。 您可以在代码段中看到行为。 最终我需要它们在小空间上具有相同的长度,但我不想使用媒体查询。 CSS网格有可能吗?

 * { color: #fff; text-shadow: 1px 1px 0 #000; box-sizing: border-box; font-family: Ubuntu, Helvetica, Verdana, Arial, sans-serif; } html { background: linear-gradient(-10deg, #C62828, #BA68C8); min-height: 100vh; font-size: 22px; } body { padding: 50px; } code { margin: 1px 5px; padding: 2px 5px 1px 5px; font-family: monospace; border-radius: 2px; border: 1px dotted #fff; } p { margin: 25px 10px; } h2 { text-align: center; margin-top: 50px; } a { text-decoration: none; } a:hover { text-decoration: underline; } .outlined { height: 200px; border: 1px solid #fff; margin-bottom: 50px; } .grid > * { color: #fff; background-color: rgba(255, 255, 255, 0.15); border: 1px solid #fff; border-radius: 2px; padding: 20px; /*margin: 10px;*/ text-align: center; } .grid a { display: block; } .grid > a:hover { background-color: rgba(255, 255, 255, 0.25); text-decoration: none; transition: background-color ease 0.5s; } .grid { display: grid; /* grid-template-rows:100px 200px; grid-template-columns: 200px auto 150px; */ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); grid-gap: 10px; border: 1px solid #fff; } .grid :nth-child(1) { grid-column: span 2; } .grid :nth-child(2) { grid-column: span 3; } .grid :nth-child(3) { grid-column: span 2; } .grid :nth-child(4) { grid-column: span 3; }
 <html> <head> <link rel="stylesheet" href="css/base.css"> <link rel="stylesheet" href="css/main.css"> <!-- Remove this line for offline development: --> </head> <body> <div class="grid"> <div>Grid item 1</div> <div>Grid item 2</div> <div>Grid item 3</div> <div>Grid item 4</div> </div> </body> </html>

您可以为此尝试使用 flexbox:

 * { color: #fff; text-shadow: 1px 1px 0 #000; box-sizing: border-box; font-family: Ubuntu, Helvetica, Verdana, Arial, sans-serif; } html { background: linear-gradient(-10deg, #C62828, #BA68C8); min-height: 100vh; font-size: 22px; } body { padding: 50px; } .grid { display: flex; flex-wrap:wrap; border: 1px solid #fff; } .grid>* { color: #fff; background-color: rgba(255, 255, 255, 0.15); border: 1px solid #fff; border-radius: 2px; padding: 20px; margin: 5px; flex-basis:0; flex-grow:2; min-width:300px; text-align: center; } /* to keep only two per line*/ .grid:before { content:""; flex-basis:100%; } /**/ /* make the first two before the pseudo element*/ .grid *:nth-child(-n + 2) { order:-1; } /* */ /* 2 and 4 will grow more */ .grid *:nth-child(even) { flex-grow:3 }
 <div class="grid"> <div>Grid item 1</div> <div>Grid item 2</div> <div>Grid item 3</div> <div>Grid item 4</div> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM