简体   繁体   中英

How to create js and html css

Responsive width and height for a group of squares

I'm creating a grid of 1:1 squares. The user can keep adding squares and I want the size of the squares to be maintained at their aspect ratio but resize accordingly. The tricky part is I want the square to always be visible on the page - that is to say that there is no scrolling and the webpage would be responsive with width and height.

I have created an example that adds a square every second while testing this. However, I am unable to get it working with the height part. I have been able to get it working with the width.

 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>

I'm not using any ui libraries like bootstrap, just vanilla html, css and javascript.

One way would be to automatically scroll to the bottom on the screen as each square is added. I added this line window.scrollTo(0,document.body.scrollHeight); to your code which makes it scroll down as a new line is created.

 setInterval(() => { //console.log(document.getElementsByClassName('square-container')[0]); document.getElementsByClassName('square-container')[0].innerHTML += (" <div class = 'square' > < /div>"); window.scrollTo(0,document.body.scrollHeight); }, 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>

Otherwise if you meant that you want the squares to resize so that all of they would all fit to the height of the window that would be different. I had a look around to see if something like this could be done but could not figure it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM