How can you force a line break on an inline-block element with CSS, after a specific number of elements?

I'm struggling to arrange a list of divs in a grid layout using only CSS, but I can't seem to make it work properly. I've explored using white-space: wrap, but that's supposed to be applied to the parent element, so it doesn't solve my problem. I also experimented with clear, but had no success. Can anyone suggest an approach that would work for any number of elements per row? The code provided is intended for three elements per line.

The reason for sticking to CSS is that this code is designed to allow users to display entries horizontally, vertically, or as a customizable grid (with 'n' representing the configurable value of elements per row).

Intended grid view display (when n=3):

Entry 1 | Entry 2 | Entry 3
--------+---------+--------
Entry 4 | Entry 5 | Entry 6
--------+---------+--------
Entry 7 | Entry 8 | Entry 9

#results.grid {
  padding-top: 40px;
}
#results.grid .entry {
  display: inline-block;
}
#results.grid .entry:nth-child(3n+1) {
  background-color: yellow;
  display: block;
}
<div id="results" class="results grid">

  <div class="entry">Entry 1</div>
  <div class="entry">Entry 2</div>
  <div class="entry">Entry 3</div>

  <div class="entry">Entry 4</div>
  <div class="entry">Entry 5</div>
  <div class="entry">Entry 6</div>

  <div class="entry">Entry 7</div>
  <div class="entry">Entry 8</div>
  <div class="entry">Entry 9</div>
</div>

Check out the JSFiddle here: https://jsfiddle.net/rn05gns1/

Answer №1

Try using float instead of inline block:

#results.grid .entry {
   float: left;
}

#results.grid .entry:nth-child(3n+1){
   background-color: yellow;
   clear: left;
}

$(document).ready(function() {
  $('#mode').change(function() {
    $('#results').removeClass();
    $('#results').addClass($(this).val());
  })
})
#controls {
  position: fixed;
  z-index: 4;
  background-color: white;
  width: 100%;
  padding: 4px
}
.entry {
  width: 200px;
  height: 150px;
  border: solid 1px black;
  margin: 5px;
}
#results.horizontal {
  overflow-x: scroll;
  overflow-y: hidden;
  width: 100%;
  white-space: nowrap;
  padding-top: 40px;
}
#results.horizontal .entry {
  display: inline-block;
}
#results.vertical {
  position: absolute;
  top: 40px;
  bottom: 0;
  overflow-y: scroll;
  overflow-x: hidden;
}
#results.grid .entry.vertical {
  display: block;
}
#results.grid {
  padding-top: 40px;
}
#results.grid .entry {
  float: left;
}
#results.grid .entry:nth-child(3n+1) {
  clear: left;
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results" class="results grid">

  <div class="entry">Entry 1</div>
  <div class="entry">Entry 2</div>
  <div class="entry">Entry 3</div>

  <div class="entry">Entry 4</div>
  <div class="entry">Entry 5</div>
  <div class="entry">Entry 6</div>

  <div class="entry">Entry 7</div>
  <div class="entry">Entry 8</div>
  <div class="entry">Entry 9</div>
</div>

Answer №2

Here is a suggestion that may be effective depending on your website layout and responsiveness requirements.

Instead of using inline-block elements, try floating your .entry items to the left and adding overflow: auto to the parent container to contain the floated elements within #results. This method prevents the floated .entry elements from affecting other elements outside of #results.

To ensure proper alignment, you can clear the floats after every n-th element. Create classes like .n3, .n4, etc., and utilize the nth-child selector to add clear:left to the first item in each row.

If there are extra elements, they will create partially filled rows, maintaining visual consistency.

On wider screens, your rows should function as intended. When viewing on smaller screens, the elements will wrap. How this wrapping is handled can be customized based on your specific layout needs.

.entry {
  width: 100px;
  height: 75px;
  border: solid 1px black;
  margin: 5px;
}
#results.grid {
  border: 1px dotted gray;
  overflow: auto;
}
#results.grid .entry {
  float: left;
}
#results.grid.n3 .entry:nth-child(3n+1) {
  background-color: yellow;
  clear: left;
}
#results.grid.n4 .entry:nth-child(4n+1) {
  background-color: green;
  clear: left;
}
<h3>Example 1: n=3</h3>
<div id="results" class="results grid n3">

  <div class="entry">Entry 1</div>
  <div class="entry">Entry 2</div>
  <div class="entry">Entry 3</div>

  <div class="entry">Entry 4</div>
  <div class="entry">Entry 5</div>
  <div class="entry">Entry 6</div>

  <div class="entry">Entry 7</div>
  <div class="entry">Entry 8</div>
  <div class="entry">Entry 9</div>
</div>

<h3>Example 2: n=4</h3>
<div id="results" class="results grid n4">

  <div class="entry">Entry 1</div>
  <div class="entry">Entry 2</div>
  <div class="entry">Entry 3</div>

  <div class="entry">Entry 4</div>
  <div class="entry">Entry 5</div>
  <div class="entry">Entry 6</div>

  <div class="entry">Entry 7</div>
  <div class="entry">Entry 8</div>
  <div class="entry">Entry 9</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

"Emphasizing the Html.ActionLink menu for improved user navigation and

Currently, I am facing an issue with my menu. I want to clear previously visited links while keeping the current one styled as a:visited in CSS. Although I have attempted to achieve this, unfortunately, the code is not functioning properly. Here is what I ...

What is the best way to ensure my inline-block table extends to 100% width?

I have some code below that I'm working on to achieve a look similar to this image: https://i.sstatic.net/744M7.jpg One thing I'm struggling with is how to extend the table header all the way to the right. Additionally, I need help adding more s ...

Is it possible to utilize the if/else if command within an HTML file?

I'm having trouble with using the if command in a JavaScript script within an HTML document. I've attempted various similar commands, but none seem to be working as expected. Any suggestions or solutions? ...

HTML5 pattern grouping feature is not functioning as expected

I am attempting to validate this regular expression pattern="([a-zA-Z]+[0-9]*){4,}", which essentially means: It must always start with an alphabetic character. If a number is included, there must be at least 4 characters in total; for example, aaaa would ...

Reorganizing bootstrap columns for mobile devices

I am currently working on a specific layout design, which can be viewed https://i.sstatic.net/IjlHG.png. Below is the code structure for this layout: <div className="row"> <div className="col"> A </div> <div className="col- ...

Linking URLs in an Android TextView with the <a href> tag

When creating a TextView dynamically, I encountered an issue with setting the text as linkable. The desired text value was "Google". After referring to various resources on the internet and blogs, such as this one, I attempted different methods but did not ...

Utilizing MaterialUI and CSS to craft this stunning box

Looking to create a new MaterialUI component similar to this one: original box Struggling with implementing it using the card component, but so far it looks like: poorly designed box Here's my custom styling using makeStyles: const useStyles = ma ...

Retrieve the CSS attributes within a directive specifically designed for child elements

Currently, I am iterating through the child elements of the element to which the directive is attached, and adding mouseup and mousedown callbacks: var dragDroppables = element[0].children; for (var elementIdx = 0; elementIdx < dragDroppables. ...

What is the best way to navigate from one div to a particular slide within a slider?

Let's say I have two web pages: index.html and page.html. On page.html, there is a slider with 9 slides created using the plugin StackSlider. Now, when a link on index.html is clicked, I want to navigate to a specific slide, like slide number 4, on pa ...

Jquery not allowing changes and blurring on section tag

After making changes to the contenteditable area and clicking off, nothing happens. This is because the function it's trying to send data to has not been created yet, so an 'failure' alert should appear. Similar code has worked fine for me i ...

Several instances of @page found within the CSS file

Is it possible to include multiple @page elements in a single HTML file? I am interested in this approach for printing various documents: For example, there are multiple invoices, each consisting of multiple pages. The first page of each invoice needs to ...

How can I retrieve the current background color and revert it back after a .hover event?

I am trying to use the .hover function to change the background color of a menu. Each menu item has a different background color, so I want it to return to its original color when the user hovers off. In other words, I want the script to read the current b ...

Angular creating numerous ng-loops

I am encountering an issue in my angular application (angular 1.4.9) where multiple ng-repeats are being generated unexpectedly. This problem occurs when I implement the following code: HTML: <div class="form-group col-md-3"> <input ng-model=" ...

Chrome is throwing a syntax error with an unexpected token in jQuery replaceWith

jQuery('div#top').replaceWith('<div id="top"> </div>') When I try to replace the entire content of the top div using jQuery, Chrome gives me an error: "Uncaught SyntaxError: Unexpected token" on the first line. I'm no ...

What is the best way to maintain whitespace in CSS while disregarding line breaks?

The white-space property in CSS-3 offers the pre-wrap value, which maintains whitespace and line breaks while wrapping as needed, along with the pre-line value that collapses whitespace but retains line breaks and wraps when necessary. However, there is c ...

Choose multiple options, with a maximum limit of 2 selections

I am currently working with a multiselect feature for various subjects. I would like to limit the selection to a maximum of 2 options and disable the rest. Additionally, if a user deselects an option, it should become available again for selection. <se ...

Use jQuery or JavaScript to incorporate HTML elements into your webpage

I have created an agenda system with weeks, but I am looking for an option that allows the user to add unlimited weeks. HTML <h1>Agenda</h1> <div class="balkje dicht"> <h2>WEEK 1</h2> <div> <div class="col1 ...

Position Bootstrap 5 modal footer elements to the left and right for an enhanced visual

Can anyone assist me with customizing the Bootstrap 5 modal footer? I am looking to align a text (either using span or label) to the left and a button to the right within the modal footer. I came across this solution and attempted to implement it by cha ...

Guide on incorporating HTML data into an existing webpage

Requesting assistance in creating an HTML page that features a dynamic drop-down menu. The drop-down should trigger a list to appear upon selection, which can be sourced from either a text file or plain HTML document. The envisioned functionality involves ...

What is the best way to eliminate borders on a span element so they collapse seamlessly?

When using the tryit editor on this html and narrowing the result window (to around 200px), the border ends up inside the span as it spans across multiple lines. Is there a way to make the border "collapse" so that it forms a single irregular border around ...