我正在创建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>
我不使用引导程序之类的ui库,而仅使用普通html,css和javascript。
答案 0 :(得分:1)
使用Float而不是wrap。设置方形容器显示块。
<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;
}
答案 1 :(得分: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>