一组正方形的响应式宽度和高度

3
我正在创建一个1:1的正方形网格。用户可以不断地添加正方形,我希望正方形的大小保持它们的长宽比,但会相应地调整大小。麻烦的是,我希望这个正方形始终可见于页面上 - 也就是说,没有滚动条,并且网页会随着宽度和高度而响应。
我已经创建了一个示例,每秒钟添加一个正方形来测试。然而,我无法让它在高度部分工作。我已经成功让它在宽度上工作了。

setInterval(() => {
  //  console.log(document.getElementsByClassName('square-container')[0]);
  document.getElementsByClassName('square-container')[0].innerHTML += ("<div class='square'></div>");
}, 1000);
.square-container {
  display: flex;
  flex-wrap: wrap;
}

.square {
  position: relative;
  flex-basis: calc(33.333% - 10px);
  margin: 5px;
  box-sizing: border-box;
  background: red;
  transition: background 1s;
}

.square::before {
  content: "";
  display: block;
  padding-top: 100%;
}
<div class="square-container">
  <div class="square"></div>
</div>

我没有使用像bootstrap这样的UI库,只使用了原生的HTML、CSS和JavaScript。

你是指“高度部分”是什么意思? - Kilmazing
2个回答

1
我可以建议一种纯JavaScript的方法吗?基本上,只需设置一个初始值,让JavaScript在每次添加正方形时进行所有计算。

// Function to resize the squares
function resizeSquares(){
    // Get the squares
    squares = document.getElementsByClassName('square');
    for (i=0;i<squares.length;i++) {
        // Set the width of the square according to the window width
        squares[i].style.width = document.body.clientWidth / squarePerRow + 'px';
        // Set the height of the square to its width to keep the aspect ratio
        squares[i].style.height = squares[i].style.width;
    }
}

// Set initial square capacity for each row
    squarePerRow = 3;

// Inicialize the size of the squares
resizeSquares();

setInterval(function(){
    // Add a square
    document.getElementById('container').innerHTML += '<div class="square"></div>';
    // Check if squares exceeds the window
    if(document.body.clientHeight > document.documentElement.clientHeight) {
        // If they do, add one square capacity per row
        squarePerRow = squarePerRow + 1;
    }
    // Resize the squares
    resizeSquares()
}, 1000)
#container {
    display: flex;
    flex-wrap: wrap;
}

.square {
    background: red;
    border: 5px solid white;
    box-sizing: border-box;
    transition: all, 0.5s;
}
<div id="container">
    <div class="square"></div>
</div>


谢谢你的回复。不过,它似乎并没有完全达到预期效果。它看起来有些卡顿,但这正是我想要的效果。如果能提供一个JavaScript解决方案,那就更好了,这绝对是正确的方向。 - okayilltry

1
使用浮动而不是包裹(wrap)。将正方形容器设置为块级元素(display block)。
<div>
<div id="square-container">
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
</div>
</div>

#square-container{
  display: block
}
#square{
    float: left;
    height: 100px;
    width: 100px;
    background-color: orangered;
    margin: 1px;
}

谢谢您的回复,不过这并不完全是我想要的,因为容器溢出并需要滚动。Agustín Dorado的解决方案更接近我想要的,但还不是完全符合我的要求。 - okayilltry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接