CSS网格正方形布局 [英] CSS grid square layout

查看:107
本文介绍了CSS网格正方形布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建由正方形组成的网格/布局.每行四个正方形.正方形在屏幕调整大小时不会变形.宽度和高度必须始终保持相同(我不希望使用固定值).我必须使用CSS网格.谁能帮我吗?

I am trying to create grid/layout consists of squares. Four squares in each row. Squares can't distort on screen resize. Width and height must be the same all the time (I don't want fixed values). I must use CSS grid. Can anyone help me ?

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 5px;
}
.container div {
  background-color: red;
}

<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

推荐答案

仅使用CSS,您可以使用伪元素将纵横比始终保持为1:1,例如

With CSS only you could use a pseudoelement to keep always the aspect ratio to 1:1 , e.g.

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 5px;
}
.container div {
  background-color: red;
}

.container div::before {
  content: "";
  padding-bottom: 100%;
  display: inline-block;
  vertical-align: top;
}

<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

这篇关于CSS网格正方形布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆