具有持久纵横比的响应式 CSS 网格

问题描述 投票:0回答:5

我的目标是创建一个包含未知数量项目的响应式网格,并将其纵横比保持在 16:9。 现在看起来像这样:

.grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, 160px);
    grid-template-rows: 1fr;
    grid-gap: 20px;
 }
.item {
    height: 90px;
    background: grey;
}
<div class="grid">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
</div>

问题是,项目不会随着屏幕尺寸缩放,导致正确的位置出现边距。但是,当使用例如

grid-template-columns: repeat(auto-fit, minmax(160p, 1fr))
使网格适应屏幕尺寸并删除
height: 90px;
时,宽高比不会持续。

也许没有CSS网格有更好的解决方案? (也许使用javascript)

html css sass responsive-design css-grid
5个回答
20
投票

您可以利用百分比填充基于宽度这一事实。

这篇 CSS 技巧文章很好地解释了这个想法:

...如果你有一个 500px 宽的元素,并且 padding-top 为 100%, 顶部内边距将为 500px。

这不是一个完美的正方形吗,500px × 500px?是的!一个方面 比率!

如果我们强制元素的高度为零(height: 0;)并且不这样做 有任何边界。那么填充将是盒模型的唯一部分 影响高度,我们就会得到正方形。

现在想象一下,我们使用 56.25%,而不是 100% 顶部填充。那个会发生 完美的16:9比例! (9 / 16 = 0.5625).

因此,为了使列保持纵横比:

  1. 按照您的建议设置列宽:

    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr))
    
  2. 向项目添加伪元素以保持 16:9 的宽高比:

    .item:before {
      content: "";
      display: block;
      height: 0;
      width: 0;
      padding-bottom: calc(9/16 * 100%);
    }
    

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
  grid-template-rows: 1fr;
  grid-gap: 20px;
}
.item {
  background: grey;
  display: flex;
  justify-content: center;
}
.item:before {
  content: "";
  display: block;
  height: 0;
  width: 0;
  padding-bottom: calc(9/16 * 100%);
}
<div class="grid">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

Codepen 演示(调整大小看效果)


17
投票

CSS 进化:纵横比属性

我们现在可以使用

aspect-ratio
CSS4 属性(我可以使用吗?)轻松管理宽高比,无需填充和伪元素技巧。与
object-fit
结合,我们获得了非常有趣的渲染。

这里,我需要以 16/9 渲染的各种比例的照片:

section {
  display: grid;
  gap: 10px;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); /* Play with min-value */
}

img {
  background-color: gainsboro; /* To visualize empty space */
  aspect-ratio: 16/9; 
  /*
    "contain" to see full original image with eventual empty space
    "cover" to fill empty space with truncating
    "fill" to stretch
  */
  object-fit: contain;
  width: 100%;
}
<section>
  <img src="https://placeimg.com/640/360/architecture">
  <img src="https://placeimg.com/640/360/tech">
  <img src="https://placeimg.com/360/360/animals">
  <img src="https://placeimg.com/640/360/people">
  <img src="https://placeimg.com/420/180/architecture">
  <img src="https://placeimg.com/640/360/animals">
  <img src="https://placeimg.com/640/360/nature">
</section>

游乐场:https://codepen.io/JCH77/pen/JjbajYZ


5
投票

我需要与视频布局完全相同的东西,但我无法使用其他答案,因为我需要受到宽度高度的限制。基本上我的用例是一个具有一定大小、未知项目数量和固定长宽比的项目的容器。不幸的是,这不能在纯 CSS 中完成,它需要一些 JS。我找不到好的装箱算法,所以我自己写了一个(假设它可能模仿现有的算法)。

基本上我所做的就是获取最大行集并找到最佳比率的拟合。然后,我找到了保留纵横比的最佳项目边界,然后将其设置为 CSS 网格的自动调整高度和宽度。结果还是蛮不错的。

这里有一个完整的示例,展示了如何将其与 CSS 自定义属性等内容一起使用。第一个 JS 函数是计算最佳大小的主要函数。添加和删除项目,调整浏览器大小以观察其重置为最佳利用空间(或者您可以查看此 CodePen 版本)。

// Get the best item bounds to fit in the container. Param object must have
// width, height, itemCount, aspectRatio, maxRows, and minGap. The itemCount
// must be greater than 0. Result is single object with rowCount, colCount,
// itemWidth, and itemHeight.
function getBestItemBounds(config) {
  const actualRatio = config.width / config.height
  // Just make up theoretical sizes, we just care about ratio
  const theoreticalHeight = 100
  const theoreticalWidth = theoreticalHeight * config.aspectRatio
  // Go over each row count find the row and col count with the closest
  // ratio.
  let best
  for (let rowCount = 1; rowCount <= config.maxRows; rowCount++) {
    // Row count can't be higher than item count
    if (rowCount > config.itemCount) continue
    const colCount = Math.ceil(config.itemCount / rowCount)
    // Get the width/height ratio
    const ratio = (theoreticalWidth * colCount) / (theoreticalHeight * rowCount)
    if (!best || Math.abs(ratio - actualRatio) < Math.abs(best.ratio - actualRatio)) {
      best = { rowCount, colCount, ratio }
    }
  }
  // Build item height and width. If the best ratio is less than the actual ratio,
  // it's the height that determines the width, otherwise vice versa.
  const result = { rowCount: best.rowCount, colCount: best.colCount }
  if (best.ratio < actualRatio) {
    result.itemHeight = (config.height - (config.minGap * best.rowCount)) / best.rowCount
    result.itemWidth = result.itemHeight * config.aspectRatio
  } else {
    result.itemWidth = (config.width - (config.minGap * best.colCount)) / best.colCount
    result.itemHeight = result.itemWidth / config.aspectRatio
  }
  return result
}

// Change the item size via CSS property
function resetContainerItems() {
  const itemCount = document.querySelectorAll('.item').length
  if (!itemCount) return
  const container = document.getElementById('container')
  const rect = container.getBoundingClientRect()
  // Get best item bounds and apply property
  const { itemWidth, itemHeight } = getBestItemBounds({
    width: rect.width,
    height: rect.height,
    itemCount,
    aspectRatio: 16 / 9,
    maxRows: 5,
    minGap: 5
  })
  console.log('Item changes', itemWidth, itemHeight)
  container.style.setProperty('--item-width', itemWidth + 'px')
  container.style.setProperty('--item-height', itemHeight + 'px')
}

// Element resize support
const resObs = new ResizeObserver(() => resetContainerItems())
resObs.observe(document.getElementById('container'))

// Add item support
let counter = 0
document.getElementById('add').onclick = () => {
  const elem = document.createElement('div')
  elem.className = 'item'
  const button = document.createElement('button')
  button.innerText = 'Delete Item #' + (++counter)
  button.onclick = () => {
    document.getElementById('container').removeChild(elem)
    resetContainerItems()
  }
  elem.appendChild(button)
  document.getElementById('container').appendChild(elem)
  resetContainerItems()
}
#container {
  display: inline-grid;
  grid-template-columns: repeat(auto-fit, var(--item-width));
  grid-template-rows: repeat(auto-fit, var(--item-height));
  place-content: space-evenly;
  width: 90vw;
  height: 90vh;
  background-color: green;
}

.item {
  background-color: blue;
  display: flex;
  align-items: center;
  justify-content: center;
}
<!--
Demonstrates how to use CSS grid and add a dynamic number of
items to a container and have the space best used while
preserving a desired aspect ratio.

Add/remove items and resize browser to see what happens.
-->
<button id="add">Add Item</button><br />
<div id="container"></div>


0
投票

也许我无法理解这个问题,但是你打算如何保持项目宽高比 16:9,同时想要随屏幕宽度缩放项目?

如果您对屏幕尺寸之间宽度增大的项目感到满意,那么这可以工作:

.grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    grid-template-rows: 1fr;
    grid-gap: 20px;
 }
.item {
    height: 90px;
    background: grey;
}
<div class="grid">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
</div>


0
投票

Chad Retz 的答案几乎正是我想要的,但它似乎有一些奇怪的行为

在 Fiverr 上的开发人员的帮助下我对其进行了一些修改,看起来效果更好。

// Get the best item bounds to fit in the container. Param object must have
// width, height, itemCount, aspectRatio, maxRows, and minGap. The itemCount
// must be greater than 0. Result is single object with rowCount, colCount,
// itemWidth, and itemHeight.
function getBestItemBounds(config) {
  const actualRatio = config.width / config.height
  console.log(actualRatio)
  
  // Go over each row count find the row and col count with the closest ratio.
  let best
  console.log(config.aspectRatio)
  for (let rowCount = 1; rowCount <= config.maxRows; rowCount++) {
    // Row count can't be higher than item count
    if (rowCount > config.itemCount) continue
    
    // calc column count
    const colCount = Math.ceil(config.itemCount / rowCount)

    // Get the width/height ratio of container for this row,col count
    const ratio = (config.aspectRatio * colCount) / rowCount

    // calc actual item width, height for this row,col layout
    let itemHeight;
    let itemWidth;
    // If the best ratio is less than the actual ratio, it's the height that determines the width, otherwise vice versa.
    if (ratio < actualRatio) {
     itemHeight = (config.height - (config.minGap * rowCount)) / rowCount
     itemWidth = itemHeight * config.aspectRatio
    } else {
     itemWidth = (config.width - (config.minGap * colCount)) / colCount
     itemHeight = itemWidth / config.aspectRatio
    }

    // calc total area of all elements
    var totalItemArea = config.itemCount * itemHeight * itemWidth
    // we want to maximize usage of container area, so minimize difference between container area and total area of all items
    var diff = (config.width * config.height) - totalItemArea
    if (!best || diff < best.diff) {
      best = { itemWidth, itemHeight, ratio, diff }
    }
  }
  
  const result = { itemWidth: best.itemWidth, itemHeight: best.itemHeight }

  console.log(result)
  return result
}

// Change the item size via CSS property
function resetContainerItems() {
  const itemCount = document.querySelectorAll('.item').length
  if (!itemCount) return
  const container = document.getElementById('container')
  const rect = container.getBoundingClientRect()
  // Get best item bounds and apply property
  const { rowCount, colCount, itemWidth, itemHeight } = getBestItemBounds({
    width: rect.width,
    height: rect.height,
    itemCount,
    aspectRatio: 16 / 9,
    maxRows: 10,
    minGap: 5
  })
  container.style.setProperty('--item-width', itemWidth + 'px')
  container.style.setProperty('--item-height', itemHeight + 'px')
}

// Element resize support
const resObs = new ResizeObserver(() => resetContainerItems())
resObs.observe(document.getElementById('container'))

// Add item support
let counter = 0
document.getElementById('add').onclick = () => {
  const elem = document.createElement('div')
  elem.className = 'item'
  const button = document.createElement('button')
  button.innerText = 'Delete Item #' + (++counter)
  button.onclick = () => {
    document.getElementById('container').removeChild(elem)
    resetContainerItems()
  }
  elem.appendChild(button)
  document.getElementById('container').appendChild(elem)
  resetContainerItems()
}
#container {
  display: inline-grid;
  grid-template-columns: repeat(auto-fit, var(--item-width));
  grid-template-rows: repeat(auto-fit, var(--item-height));
  place-content: space-evenly;
  width: 90vw;
  height: 90vh;
  background-color: green;
}

.item {
  background-color: blue;
  display: flex;
  align-items: center;
  justify-content: center;
}
<!--
Demonstrates how to use CSS grid and add a dynamic number of
items to a container and have the space best used while
preserving a desired aspect ratio.

Add/remove items and resize browser to see what happens.
-->
<button id="add">Add Item</button><br />
<div id="container"></div>

© www.soinside.com 2019 - 2024. All rights reserved.