【问题标题】:Responsive Square in CSSCSS中的响应式正方形
【发布时间】:2021-12-20 03:36:14
【问题描述】:

CSS grid layout 有没有办法让项目高度匹配项目宽度,确保项目是方形的?

例如我们可以让宽度和高度为“网格容器宽度的 25%”吗?

【问题讨论】:

  • AFAIK,没有。 :(
  • 如果网格布局不能制作出通常称为网格的结构的响应版本,这有点讽刺。
  • 哈哈...同意你的朋友! :)
  • AFAIK,是的 ;-)
  • 您在寻找这样的东西吗? jsfiddle.net/ezzsgkgg

标签: css responsive aspect-ratio css-grid


【解决方案1】:

当然可以!

CSS

.wrapper{ display: grid;  grid-template-columns: repeat(4, 1fr);}
.wrapper > div { border: 1px solid black;position:relative;}
.wrapper > div:before {display: table; padding-top: 100%; content: '';}
.content{position: absolute;top:0; left:0; width:100%;height:100%;display:flex; justify-content:center; align-items:center;}

HTML

<div class="wrapper">
  <div><div class="content">1</div></div>
  <div><div class="content">2</div></div>
  <div><div class="content">3</div></div>
  <div><div class="content">4</div></div>
</div>

生产示例http://www.montblancnaturalresort.com

片段

.wrapper {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}

.wrapper>div {
  border: 1px solid black;
  position: relative;
}

.wrapper>div:before {
  display: table;
  padding-top: 100%;
  content: '';
}

.content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="wrapper">
  <div>
    <div class="content">1</div>
  </div>
  <div>
    <div class="content">2</div>
  </div>
  <div>
    <div class="content">3</div>
  </div>
  <div>
    <div class="content">4</div>
  </div>
</div>

【讨论】:

  • 这真的很酷 --- 我已经在一段代码中使用了它,我可以看到它对我有用。谢谢!不过我有一个请求——你能解释一下伪元素是如何为内容设置样式的吗?为什么它的存在和display:table; padding-top:100%; 可以保持高度/宽度同步?
【解决方案2】:

虽然已经回答了。但是自从提出这个问题以来,CSS 已经进行了多次更新。有了新的属性,制作一个正方形太容易了。 使用aspect-ratio 属性,您可以在矩形、圆形、正方形等中构建响应式形状。

:root {
  --square: 800px;
  --background: teal;
}
.square {
    background: var(--background);
    width: 100%;
    max-width: var(--square);
    height: auto;
    aspect-ratio: 1/1;
}
&lt;div class="square"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 2014-05-05
    • 1970-01-01
    相关资源
    最近更新 更多