【问题标题】:How to create a variable width squares using css grid layout?如何使用 CSS 网格布局创建可变宽度的正方形?
【发布时间】:2018-05-13 20:57:01
【问题描述】:

有没有办法让宽度基于 fr 单位的网格单元格动态调整它们的高度以保持正方形?

另外,我希望做到这一点没有 JS

下面的小提琴有一些示例代码。具有“sqaure”类的 div 是我想要动态调整它们的高度以匹配它们的宽度(这是 1fr 所以它会改变)

https://jsfiddle.net/bpk0sLvL/403/

.holder {
  display: grid;
  grid-template-columns: 1fr 1fr;
  column-gap: 4px;
  row-gap: 4px;
}

.box {
  background-color: #ccc;
}

.wide {
  grid-column-start: 1;
  grid-column-end: 3;
}
<div class="holder">
  <div class="box wide">
    <p>This can be any height</p>
    <p>All these divs are sized based on fr, so I want to have the two square divs stay square as they dynamically resize </p>
  </div>
  <div class="box sqaure">
    This needs to be a sqaure
  </div>
  <div class="box sqaure">
    This needs to be a square as well
  </div>
</div>

【问题讨论】:

  • 你可以试试填充技巧
  • 填充技巧是什么?
  • 尝试padding-top:75% 在你的广场课上看看
  • @GeorgeKendros 也许check this post 关于如何保持 div 的纵横比

标签: html css css-grid


【解决方案1】:

你需要:

  1. 识别.square的宽度;和
  2. 确保.square 的高度等于该宽度。

一行javascript就可以识别.square的宽度:

var squareWidth = document.getElementsByClassName('square')[0].offsetWidth;

你可以用两行javascript确保.square的高度等于那个宽度:

var holder = document.getElementsByClassName('holder')[0];
holder.style.gridTemplateRows = 'auto ' + squareWidth + 'px';

工作示例:

function calculateSquareHeight() {

    var holder = document.getElementsByClassName('holder')[0];
    var squareWidth = document.getElementsByClassName('square')[0].offsetWidth;
    holder.style.gridTemplateRows = 'auto ' + squareWidth + 'px';
}

window.addEventListener('load', calculateSquareHeight, false);
window.addEventListener('resize', calculateSquareHeight, false);
.holder {
display: grid;
grid-template-columns: 1fr 1fr;
grid-column-gap: 4px;
grid-row-gap: 4px;
}

.box {
background-color: #ccc;
}

.wide {
grid-column-start: 1;
grid-column-end: 3;
}
<div class="holder">
<div class="box wide">
<p>This can be any height</p>
<p>All these divs are sized based on fr, so I want to have the two square divs stay square as they dynamically resize </p>
</div>

<div class="box square">
This needs to be a square
</div>

<div class="box square">
This needs to be a square as well
</div>
</div>

【讨论】:

  • 对不起。我现在意识到我应该在最初的问题中明确表示我希望有一种方法可以单独使用 CSS。建议的方法(将高度设置为 0 并将填充设置为 100)
  • 没关系 - 我了解到您正在寻找一种纯 CSS 方法。我经常建议 CSS 方法,而其他人建议使用 jQuery 或 Javascript 方法。但我在上面发布了脚本,因为据我所知,没有令人满意的 CSS 方法。我知道填充“技巧”,但这是一种技巧,并不总是理想的。我真正想看到的是 CSS 中的 ratio 函数,所以你可以写:height: ratio(1/1);
  • 同意,在尝试了 padding hack 并看到它是多么的喜怒无常之后,我实际上最终在 JS 中完成了它。我认为拥有这样的 css 功能会很酷。甚至有模仿 vh 和 vw 的 ew 和 eh 单位,除了当前元素。如果我们有这个,那么我们至少可以使用 calc 函数建立比率。
  • 是的,同意 - eweh 长度将是一个非常聪明的创新。甚至可能还有 pwph 长度(指元素的直接父级)。
猜你喜欢
  • 1970-01-01
  • 2019-07-22
  • 2012-01-17
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 2018-02-19
  • 2015-11-06
相关资源
最近更新 更多