【问题标题】:squared boxes by height (not width) to create equal width (aspect ratio)按高度(不是宽度)平方框以创建相等的宽度(纵横比)
【发布时间】:2019-10-13 01:45:39
【问题描述】:

我知道:before { padding-bottom } 的平方解。这仅适用于宽度值,因为填充始终使用与父宽度的关系。 - 但这正是我的问题。

我只有一个固定的 HEIGHT 值(由父容器),我需要该高度值的方形框。我不喜欢用JS。如果有解决方案REPLACE用纯CSSSTATIC WIDTH值,请告诉我!

这是一个简单的代码示例:

div.wrapper {
  height: 70px;
  padding: 5px;
  background: black;
}

div.box {
  float: left;
  width: calc(70px - 10px); /* here is that static value for width, but better would be a relation to (parent) height */
  height: calc(100% - 10px);
  margin: 5px;
 }

div.box.b1 {
  background: orange;
}

div.box.b2 {
  background: red;
}

div.box.b3 {
  background: green;
}

div.box.b4 {
  background: dodgerblue;
}

div.box.b5 {
  float: right;
  background: grey;
}
<div class="wrapper">
  <div class="box b1">A</div>
  <div class="box b2">B</div>
  <div class="box b3">C</div>
  <div class="box b4">D</div>
  <div class="box b5">E</div>
</div>

我也在寻找“css-3 网格”,但没有找到好的解决方案。但如果有人知道这个问题,请告诉我! :)

PS:仅供参考...父级的宽度始终为 100%(或 vw)。我想创建一个具有定义高度的导航栏,可以通过媒体查询进行更改。但只有高度值,而不是父容器的宽度值。

PPS:我在这里发现了一些关于该问题的更多问题,但没有人了解询问者。因为我们不是在寻找“var height = width”,而是在寻找“var width = height”。 ;)

【问题讨论】:

  • 如果您要定义父级的高度,然后使用 CSS 变量在子级的高度/宽度中重用相同的值
  • 是的,但这只会对 IE 兼容性不利。 (i.stack.imgur.com/HiVo3.png) :/

标签: css height css-grid aspect-ratio


【解决方案1】:

好的,我找到了一种使用 grid 和 css-vars 的方法...

:root {
  --box-spacing: 10px;
  --box-length: 60px;
}

.grid {
  display: grid;
  grid-template-columns: repeat(4, var(--box-length)) auto var(--box-length);
  grid-auto-rows: var(--box-length);
  grid-template-areas: 
    "a b c d . e";
  grid-gap: var(--box-spacing);
  padding: var(--box-spacing);
  background:black;
}

.grid > :nth-child(1) {
  grid-area: a;
  background:orange;
}

.grid > :nth-child(2) {
  grid-area: b;
  background:red;
}

.grid > :nth-child(3) {
  grid-area: c;
  background:green;
}

.grid > :nth-child(4) {
  grid-area: d;
  background:blue;
}

.grid > :nth-child(5) {
  grid-area: e;
  background:grey;
}
<div class="grid">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
</div>

我只是对宽度和宽度长度使用相同的 var()。而grid-template-areas 允许它使用. 作为第五个位置的空列。该列具有自动宽度。

这不是美丽,但它有效......如果你有更好的解决方案,告诉我! :)

【讨论】:

    猜你喜欢
    • 2021-06-23
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 2014-07-01
    • 2014-04-17
    • 2013-09-23
    • 2019-12-03
    相关资源
    最近更新 更多