Tips for achieving a precise amount of boxes in each row

Is it possible to only have 5 boxes per line and then the next one goes to the next line using CSS?

https://i.stack.imgur.com/L7vr4.png

.box {
  border-color: #32ff00;
  border-width: 4px;
  border-style: dotted;
  width: 170px;
  height: 200px;
  float: left;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

Answer №1

If you prefer to continue using the float property (as shown in your initial query), you can apply this specific CSS rule:

.box:nth-child(5n+1) {
  clear: left;
}

This directive will shift every fifth plus one instance of the .box element (e.g., the 6th, 11th, 16th, and so on) onto a new line. Please keep in mind that there should be no other elements interspersed among them at the same HTML level for this method to function correctly.

(please note: I reduced the size of the boxes to better demonstrate the outcome within the snippet window)

.box {
  border-color: #32ff00;
  border-width: 4px;
  border-style: dotted;
  width: 80px;
  height: 100px;
  float: left;
  margin: 5px;
}

.box:nth-child(5n+1) {
  clear: left;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

Answer №2

To create a grid layout, we simply need to modify the display property of the parent element and use the grid-template-columns along with grid-template-rows property.

#parent {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-template-rows: repeat(2, 1fr);
  grid-gap: 20px
}

.box {
  border-color: #32ff00;
  border-width: 4px;
  border-style: dotted;
  width: 170px;
  height: 200px;
  float: left;
}
<div id="parent">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

This CSS rule will divide the layout into 5 columns and 2 rows effectively.

Answer №3

For a simpler approach than using float, consider utilizing either Flexbox or Grid. Here's an example using Grid:

.boxes {
  display: grid;
  grid-template-columns: repeat(5, 100px);
  gap: 1rem; /* to have some space between the boxes */
}
.box {
  border-color: #32ff00;
  border-width: 4px;
  border-style: dotted;
  height: 100px;
}
<div class="boxes">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

Answer №4

This method provides a classic solution that is backwards compatible with older browsers and does not rely on grid or flexbox technology.

  • Start by enclosing the boxes within a container with a specific width (fixed, percentage, auto, etc.) to restrict the line width of the boxes. Keep in mind that the container width should be equal to box-width multiplied by the number of boxes per line if there are no spaces between them.

  • Set the display property of the boxes to inline-block to position them like characters.

  • Eliminate all whitespace between the boxes in the HTML markup. Failure to do so will result in spaces appearing between the boxes. Alternatively, you can set the font size to 0 in CSS rather than removing HTML whitespaces.

  • To ensure compatibility with narrower screens, limit the width using max-width: 100%. By doing this, you can specify the maximum number of columns while allowing the browser to determine the appropriate number based on screen or parent element width.

For centering:

  • Center the boxes within the container using text-align: center on the container.

  • Restore the text alignment inside the boxes, for example, by applying text-align: left directly to the boxes.

  • Center the container itself by using margin: auto (if the container has a position of absolute or relative, use margin: 0 auto to avoid vertical centering). Feel free to adjust the top and bottom margins of the container as needed. To create horizontal space around the boxes, utilize padding on the container.

.container {
  width: 850px;

  /* Use less columns on narrow screens. */
  max-width: 100%;
  
  /* For centering. */
  margin: auto;
  text-align: center;
}

.box {
  border-color: #32ff00;
  border-width: 4px;
  border-style: dotted;
  width: 170px;
  height: 200px;
  display: inline-block;
  text-align: left;
}
<div class="container">
  <div class="box"></div><!--
  --><div class="box"></div><!--
  --><div class="box"></div><!--
  --><div class="box"></div><!--
  --><div class="box"></div><!--
  --><div class="box"></div><!--
  --><div class="box"></div><!--
  --><div class="box"></div><!--
  --><div class="box"></div><!--
  --><div class="box"></div><!--
  --><div class="box"></div><!--
  --><div class="box"></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

Full comprehension with a width of 100%

Here is an example where .flex2 has 2 children. 1st child - width: 300px 2nd child - width: 100% .b{ height: 50px; } .flex2{ margin-top: 20px; display: flex; .box{ background-color: blue; width: 300px; } .box1{ backgroun ...

I've been attempting to upload application/pdf files, but I'm having trouble. Can you provide me with instructions

'<?php $allowedExts = array("jpg", "jpeg", "gif", "png"); $extension = end(explode(".", $_FILES["file"]["name"])); if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/ ...

Safari having trouble auto-playing Vimeo iframe embed

Update 6/26/23: Seems like a mysterious change occurred, as now the Vimeo video on project pages is playing automatically for me in Safari without any specific reason. It's working fine on Chrome too. Not sure if Vimeo made an update or if it's r ...

Altering calendar dates using VBA for web scraping

Seeking assistance with creating a VBA program for automatically downloading historical stock data from a website. The code I have currently works for downloading data, but I'm facing challenges in changing the date using my code. You can view the co ...

Ensure your mobile device is age 13 or over before proceeding

I am developing a project with Next js. Here, I want to render a component if it is a mobile device. However, if I use the isMobileDevice value in jsx, I get the errors below. import useTranslation from "next-translate/useTranslation"; import isM ...

Homepage divided in two sections akin to the Tumblr landing page

Have you ever visited www.tumblr.com and noticed the '30 reasons...' link on the registration page that slides up and reveals a second page? I've been trying to figure out how they achieve this cool effect. Most tutorials show how to scroll ...

Send a parameter to be used as a link attribute in a pop-up box

I am seeking a way to pass a URL for my modal that relies on extracting the adder variable from the main HTML document. While I understand how to pass variables as text (using spans) to a modal, I am unsure how to incorporate a variable in an anchor <a ...

Consolidate HTML project into a unified HTML file

In my current project, I am working with a static HTML report that is organized in the structure outlined below: 1.css 2.font 3.js 4.pages 5.attachments 6.index.html I would like to know how I can combine all these elements to create a unified 'repor ...

Restricting CSS Background Image Width to 960 Pixels

My CSS style is causing my background image to span across the whole screen instead of repeating within the 960px width of the body. body { width:960px; margin: 10px auto 10px auto; background-image:url(logo.png),url(backgroundimage.jpg); ...

The CSS code designed to limit the display to only a two-line sentence is failing to work properly in Internet Explorer

I've implemented the following CSS code to ensure that the display sentence doesn't exceed 2 lines, with the remaining text being replaced by "...". .bell-notification-max-words-display { overflow: hidden; display: -webkit-box; ...

Sending a Boolean value from a child component to its parent state in React JS

Within my application, I have implemented a login feature in the navbar component. However, I am encountering an issue with updating a variable in the main component upon successful login. Although I have successfully managed to set up the login functional ...

Guide on how to load just the content section upon clicking the submit button

Here is an example of my code: <html> <head> <title>Test Loading</title> </head> <body> <div id="header"> This is header </div> <div id="navigation" ...

Issues with Disabling the Browser's Back Button with jquery

I have been attempting to prevent the back button from functioning in a specific Browser, Microsoft Bing. Interestingly, my code works only if I click somewhere in the window first. If I don't click anywhere and try to go back directly, it still allow ...

Utilizing Bootstrap 4 to ensure the final DIV is vertically stacked and fills the remaining space in the container

Having trouble creating a responsive layout using Bootstrap 4? Specifically, when two divs wrap vertically on smaller devices, the top div pushes the lower div down, exceeding the parent container. I want the lower div to fit within the container. How can ...

Add a sound file to the server and configure the images based on the server's response

I am a newcomer to JavaScript and AJAX, and I am facing an issue while trying to upload an audio file to the server and display the image from the server response. When attempting to pass the audio file from the input tag to an AJAX call, I encounter an il ...

What is the best way to automatically adjust the size of an image to fit its

One of the challenges with the parent container is fitting an image inside it: .parent { position: relative; text-align: center; overflow: hidden; display: flex; align-items: center; align-content: center; justify-content: cente ...

The page fades in as soon as it is loaded thanks to the "

I am interested in creating a unique effect where different classes fade in on page load. Check out this webpage for reference. The linked page showcases squares in various shades of grey and color, with the desire to have them fade in at different inter ...

pull information from mongodb into angular

I am attempting to retrieve data from MongoDB, but I keep seeing [object] [object]. How can I transfer array data from MongoDB to Angular? Here is the code snippet: import { Component, OnInit } from '@angular/core'; import {HttpClient} from &quo ...

Arrange your grid system with Bootstrap Vue

There is a dataset retrieved from an API, and each item will be displayed within a div using a v-for loop. The desired layout for the grid of divs is as follows: [-- item 1 --][-- item-2 --] [-- item 3 --][-- item-4 --] [-- item 5 --][-- item-6 --] [-- ite ...

Enhance the appearance of div elements in GWT/HTML with custom styling

I am relatively new to GWT and have been exploring various options, but I have not yet found a solution to my issue. The challenge at hand involves developing a function schedule system in GWT, where I am working on designing the frontend. We currently ha ...