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

The custom classes I have created in Material UI are being overshadowed by the default classes provided by Material UI

I am trying to change the color of a TextField label to black when it is focused. I used classes in InputProps with a variable, but unfortunately, the default styling of material UI is taking precedence in chrome dev tools. Below is the code snippet. Pleas ...

Using a series of identical divs to dynamically update the image URL

Greetings! I am a newcomer to the world of web development and I have decided to hone my skills by creating a small website for my mother! My goal is to replicate a specific div multiple times while changing only the image URL and the heading caption. < ...

How can I define the boundaries for the scrolling of a static background image?

Is there a way to limit how far a fixed background image can scroll down a page? Essentially, is it possible to change the background attachment to static when the bottom of the background image is 10px away from the bottom edge of its div container? In t ...

Creating a div with a fixed size in Tailwind CSS: A beginner's guide

I received some initial code from a tutorial and I've been having trouble setting the correct size. Despite searching through documentation for solutions, it seems like there's a fundamental aspect that I'm overlooking. The main issue is tha ...

What is the best way to incorporate the value of a textbox into a list?

I currently have a list structured like this: <p>Please choose from the following options:</p> <script type="text/javascript"></script> <select id='pre-selected-options1' multiple='multiple'> <opt ...

Generating unique identifiers for ng-model in AngularJS

Issue - ng-model is not generating dynamically. I have dynamic input boxes and I am attempting to create ng-model dynamically like test[1], test[2], etc. However, when inspecting the form with Firebug, all input elements only show - test[shiftnumber]. HT ...

What is the proper way to add process.env.PORT to the script declarations string within my package.json file?

I am facing an issue while trying to upload my file on Heroku that requires including the PORT specification. Unlike my previous projects, this project consists of only html, js, and css files instead of an index.js file. To run it, I am using "live-server ...

What is the reason CURL is unable to retrieve the HTML content of a page?

Check out the code snippet below: <?php $url = "https://www.facebook.com/login/identify?ctx=recover&lwv=110"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, C ...

Combining two flex elements with auto-growing capabilities in react-native

I am excited about using react-native to have a TextInput aligned with a MaterialIcons.Button in the same line. I have been trying to center these elements horizontally but haven't been successful with the code below: import React from 'react&apo ...

Firefoxi is the only browser that exhibits strange padding and margin behavior

Check out this webpage at: www.bit.ly/1b4dUqs Most browsers display the page correctly, but there seems to be an issue with Firefox's (latest version) handling of margin-top/padding-top styles. If anyone has a solution for this problem, please share ...

Optimizing Your HTML5 Code: Best Practices

Lately, I've come across some articles on HTML5 best practices and they all seem to emphasize the following guideline: "Prefer using id attribute over name attribute" But is this really the best approach? How can I effectively manage forms in PHP wi ...

What is the best way to arrange buttons in a row horizontally?

Desired Output I need help aligning the buttons as shown in the Desired Output image, but when I run the code, the buttons stack vertically, resulting in Output like this. I've included the HTML, CSS, and JS code below. As a beginner in UI design, I ...

Issue with ng-multiselect-dropdown where clearing selected items programmatically does not visually work as expected

Utilizing the ng-multiselect-dropdown, I have encountered an issue where deselecting an option within the object itself clears the selected items visually and in the variable array. However, when programmatically clearing the selectedItems, the variable a ...

The component triggering the redirect prematurely, interrupting the completion of useEffect

I set up a useEffect to fetch data from an endpoint, and based on the response, I want to decide whether to display my component or redirect to another page. The problem I'm facing is that the code continues to run before my useEffect completes, lead ...

How can I extract data from a swiffy animation?

Suppose I am tracking the number of mouse clicks in Flash. To do this, I have utilized the following code: import flash.events.MouseEvent; plus.addEventListener(MouseEvent.CLICK,aaa) var i:int=0; function aaa(e:MouseEvent) { i++; var a:Number ...

Styling elements with CSS to display inline blocks next to each other while taking up the full

I am facing a challenge with two text blocks of varying lengths. The left block contains short text while the right block may have lengthy content. Both blocks need to be displayed side by side, occupying 100% of the parent's width exactly. For a sim ...

Is your window.location.hash malfunctioning?

I am facing an issue with changing the background color of a <div id="services> when a specific link (index.html#services) is clicked. I have attempted to use the latest jQuery along with the jQuery Color plugin from jQuery Color. The code snippet I ...

Harnessing the power of lazysizes with WebP

I've been working on optimizing our site through the Google Lighthouse audit, and it's clear that images are a major focus. Right now, my main goal is to address the issue of 'Deter offscreen images' highlighted in the audit. To tackle ...

When the specified condition is met in HTML along with a designated URL

Is there a way I can implement an if condition in my HTML file within Codeigniter that checks the URL? Depending on whether or not it contains part of the URL, it would perform different actions. For instance: The initial URL is localhost/index.php/ca ...

Unable to create a clickable image

My approach involves using asp:Hyperlink controls to create an image that acts as a link. Here is the sample code in both aspx and C#: <asp:HyperLink ID="mainInteractiveFileLink" runat="server"> </asp:HyperLink> C# mainInteractiveFileLink ...