What is the best way to adjust the width of these elements for a perfect fit?

I'm currently working on a website where I have arranged squares in a grid layout. My goal is to make these squares perfect, with equal width and height. The only issue I'm encountering is that they tend to change between fitting two and three squares per line when resizing the page. Below is the code snippet:

const select = (querySelector) => document.querySelector(querySelector),
      selectAll = (querySelector) => document.querySelectorAll(querySelector),
      getByClass = (className) => document.getElementsByClassName(className),
      getByTag = (tagName) => document.getElementsByTagName(tagName);
function adjustSize() {
    if (select('.post')) {
        for (let i = 0; i < getByClass('post').length; i++) {
            getByClass('post')[i].style.width = getByClass('post')[i].parentElement.offsetWidth/3-10.982;
            getByClass('post')[i].style.height = getByClass('post')[0].offsetWidth;
        }
    }
    window.addEventListener('resize', adjustSize, false);
}
window.addEventListener('load', adjustSize, false);
window.addEventListener('resize', adjustSize, false);
.posts {
    font-size: 2.5em;
    font-family: 'Lato', sans-serif;
    padding: 0 25px;
    flex-wrap: wrap;
    display: flex;
    min-height: 150px;
}
.posts-items {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}
.post {
    border: 0.5px solid black;
    margin: 5px;
    width: 33%;
    overflow: hidden;
}
<div class = 'posts'>
  <div class = 'posts-items'>
    <div class = 'post'>

    </div>
    <div class = 'post'>

    </div>
    <div class = 'post'>

    </div>
    <div class = 'post'>

    </div>
  </div>
</div>

I would appreciate any assistance in ensuring that the squares maintain the correct size!

Answer №1

Make sure to include the unit of measurement for the dimensions ("px")

const get = (querySelector) => document.querySelector(querySelector),
      getAll = (querySelector) => document.querySelectorAll(querySelector),
      getClass = (className) => document.getElementsByClassName(className),
      getTag = (tagName) => document.getElementsByTagName(tagName);
function resizePosts() {
    if (get('.post')) {
        for (let i = 0; i < getClass('post').length; i++) {
            getClass('post')[i].style.width = getClass('post')[i].parentElement.offsetWidth/3-10.982 +"px";
            getClass('post')[i].style.height = getClass('post')[0].style.width;
        }
    }
}
window.addEventListener('load', resizePosts, false);
window.addEventListener('resize', resizePosts, false);
.posts {
    font-size: 2.5em;
    font-family: 'Lato', sans-serif;
    padding: 0 25px;
    flex-wrap: wrap;
    display: flex;
    min-height: 150px;
}
.posts-themselves {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}
.post {
    border: 0.5px solid black;
    margin: 5px;
    overflow: hidden;
}
<div class = 'posts'>
  <div class = 'posts-themselves'>
    <div class = 'post'>

    </div>
    <div class = 'post'>

    </div>
    <div class = 'post'>

    </div>
    <div class = 'post'>

    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The switchView feature is currently malfunctioning and unable to access the content on the next page

For my application's admin panel design, I've divided my home into containers. The aim is to display details of clicked items in Images.html and Categories.html when a menu item in the 2nd container (also known as side bar) is clicked. However, m ...

What is the best way to set a fixed width for my HTML elements?

I am facing an issue with my user registration form where error messages are causing all elements to become wider when they fail validation. I need help in preventing this widening effect. How can I achieve that? The expansion seems to be triggered by the ...

React state is not refreshing as expected

I am having trouble updating the state with new employee data. The push function is not inserting the new employee data into the state. In the addPar function, I set up a console log and it shows that the data is there, but it fails to push it to the sta ...

Setting up StrongLoop LoopBack MongoDB datasource for successful deployment on Heroku

Currently, I am utilizing LoopBack version 1.6 and have a local mongoDB server operational for development purposes with the following datasource configuration: "mongodb": { "defaultForType": "mongodb", "connector": "loopback-connector-mongodb", ...

Ensuring the safety of PHP JSON output results on a web server

I am currently developing an app using phonegap that submits and retrieves data from a MySQL database hosted on a server (website). I have successfully implemented the data submission and retrieval features in the app. The data is fetched through AJAX fro ...

Managing VueJS components and Observers during the rendering process to ensure smooth functionality in a multi-phase environment

Situation: As part of my development work, I am creating a Vue scroll component that encompasses a variable number of HTML sections. This component dynamically generates vertical page navigation, allowing users to either scroll or jump to specific page lo ...

Spinning a point around the center on a canvas

My friend and I are in the process of creating a game, and we've reached the point where we want to implement a radar system. While we have successfully designed a basic radar that displays everything in the correct positions, our next challenge is to ...

Angular model is not receiving the value of a false checkbox

One issue I am facing is with a form that includes a checkbox bound to an ng-model property. The problem arises when the checkbox is checked, as the value gets set in the model. However, when it is unchecked, the key and value remain unset, causing API val ...

jQuery is missing an essential component that is causing an error

I have successfully implemented the following JavaScript code and everything is working fine. However, I'm uncertain if my code is fully correct. I noticed that in my script, I only utilize success: function() without incorporating an error function. ...

Storing the selected radio button value in AsyncStorage using React Native: A step-by-step guide

Can anyone help me with storing the users selected radio button value in AsyncStorage? I have radio button values being retrieved from another file and assigned to labels. Here is an example of how my radio buttons are structured: import RadioButtonRN fr ...

Incorporating images with text in the navigation bar

Just dipping my toes into the world of HTML and CSS, but I need some guidance. I'm trying to incorporate images and text (for the title) in my header using a navbar. However, when I resize the window, the text doesn't move along with the image. ...

I am confused about the process of mounting components

Utilizing pattern container/representational components, I have a CardContainer component that retrieves data from a server and passes it to a Card component. Container Component: class CardContainer extends Component { state = { 'ca ...

Issue with Firefox translateZ causing only half of the content to be visible on initial load in Pure CSS Parallax configurations

Recently, I've been experimenting with creating a parallax website and have been following the helpful steps outlined by Keith Clark. However, I've run into an issue that seems to be specific to Firefox. Upon loading the site, I noticed that the ...

What is the method to identify the key responsible for triggering a textbox input event?

Suppose there is a textbox on the webpage: <input id='Sub' type='text'> To capture each time the input changes, you can use the following code: sub = document.getElementById('Sub'); sub.addEventListener('input&a ...

JavaScript Decoding JSON with varying identifiers

The JSON data provided contains information about different types of vehicles, such as cars, buses, and taxis. { _id:"7654567Bfyuhj678", result:{ CAR:[ [ "myCar1", 12233 ], [ ...

Disable functionality not functioning properly on button attribute

I've created a demo on JSFiddle here: http://jsfiddle.net/qJdaA/2/. The goal of this code is to disable the button with the ID #monitor if no checkboxes are checked. var checked = $('#status_table tr [id^="monitor_"]:checked'); if (checked. ...

Tips for using jQuery to add several image source URLs to an array

My JavaScript code uses jQuery to collect all image sources on document load and store them in an array: var sliderImg = []; sliderImg.push($('.thumbnail').children('img').attr('src')); Then, I have a click event set up to a ...

Using AngularJS to invoke the ng-required directive and trigger a function

Is it possible to make the required value dependent on a function? Something similar to this? I need to achieve this in order to dynamically change the required attribute for form inputs... HTML: Name: <input type="text" ng-model="user.name" ng-r ...

The attempt to access 'reading params' is resulting in an error due to undefined properties

Looking for some assistance in resolving an error I'm encountering. Below is a snippet of my code: const ProductScreen = ({match, history}) => { const [qty, setQty] = useState(1); const dispatch = useDispatch(); const productDetail ...

Is it possible to categorize a JSON object based on its properties and then count the occurrences of each property within

I have an array of objects containing booking information and I need to calculate the count of each booking item in every object. const arr = [ { "ID" : 1, "Name":"ABC", "Bookings":[ { & ...