How can we automatically add dividers after a certain number of elements in CSS?

Is there a way to create a responsive layout with CSS that automatically adds a divider after a certain number of elements?

For example, I have a set of elements with the class .beers, and I want to insert a .divider element after every 5th .beers element in my layout.

You can check out an example of what I'm trying to achieve in this FIDDLE

If anyone has any ideas on how to accomplish this, I would greatly appreciate the help.

Thank you!

Here is the CSS I am currently using:

.wrapper{
width:100%;
}

.content{
width:960px;
height:500px;

}

.beers{
position: relative;
width: 166px;
display:inline-block;
margin-right: 5px;
height: 107px;
margin-bottom: 20px;
padding-left: 10px;
padding-right: 10px;
text-decoration: none;
border: 1px dotted #e46a10;
}

.divider{

  display: block;
border-bottom: 1px dotted #ccc;
margin-bottom: 20px;
}

Answer №1

If you're looking to spice up your design, here's a neat trick that involves using pseudo elements creatively. By shifting your divider styles into the .beers::after pseudo element and targeting each :nth-child(5n) class, you can achieve a visually appealing effect:

.beers {
  position: relative;
  width: 166px;
  display:inline-block;
  margin-right: 5px;
  height: 107px;
  margin-bottom: 20px;
  padding-left: 10px;
  padding-right: 10px;
  text-decoration: none;
  border: 1px dotted #e46a10;
}

.beers:nth-child(5n)::after {
  display: block;
  border-bottom: 1px dotted #ccc;
  margin-bottom: 20px;
  content: "";
}

Note that if your beers are inline block elements and you want them separated every 5 items, this method might not give you exactly what you're looking for upon further examination of your code.

Answer №2

In my opinion, the 6th block will clear the 5th one and the dotted line will stretch the width of the content divs. Additionally, by adding the dotted line to the top of the 6th element, we are removing the line from the bottom of the stack if it ends on the last 5th element.

Check out the updated fiddle here: https://jsfiddle.net/onjL7kn4/4/

.wrapper {
  width: 100%;
}

.content {
  width: 960px;
  height: 500px;
}

.beers {
  position: relative;
  width: 166px;
  display: block;
  float: left;
  margin-right: 5px;
  height: 107px;
  margin-bottom: 20px;
  padding-left: 10px;
  padding-right: 10px;
  text-decoration: none;
  border: 1px dotted #e46a10;
}


.content > div:nth-of-type(5n+6) {
  clear: left;
}

.content > div:nth-of-type(5n+6):before {
  content: "";
  display: block;
  height: 1px;
  width: 960px;
  border-bottom: 1px dotted #ccc;
  transform: translateY(-12px);
}
<div align="center" class="wrapper">

  <div align="center" class="content">

    <div class="beers"></div>
    <div class="beers"></div>
    <div class="beers"></div>
    <div class="beers"></div>
    <div class="beers"></div>
    <div class="beers"></div>
    <div class="beers"></div>
    <div class="beers"></div>
    <div class="beers"></div>
    <div class="beers"></div>
    <div class="beers"></div>
    <div class="beers"></div>
    <div class="beers"></div>

  </div>

  <div>

Answer №3

To achieve the desired divider effect using only the styles within your divider class, you can utilize the nth-child selector without resorting to pseudo-elements:

.beers:nth-child(5n) {
  border-bottom: 1px dotted #ccc;
  margin-bottom: 20px;
  padding-bottom: 20px;
}
<ul>
  <li class="beers">Item</li>
  <li class="beers">Item</li>
   ...
  <li class="beers">Item</li>
  <li class="beers">Item</li>
</ul>

EDIT For compatibility with inline-block elements (assuming a five-column layout), you can use the following CSS:

.beers {
  border-bottom: 1px dotted #ccc;
  display: inline-block;
  margin-bottom: 20px;
  margin-right: -0.25em;
  padding-bottom: 20px;
  width: 20%;
}
<ul>
  <li class="beers">Item</li>
  <li class="beers">Item</li>
  ...
  <li class="beers">Item</li>
  <li class="beers">Item</li>
</ul>

Answer №4

For those times when a CSS solution just won't do the trick, we've got some javascript code options for you to choose from - pure javascript and jQuery. Take your pick:

Pure javascript: Check out jsFiddle 1

var brs = document.querySelectorAll('.beers');

for (var i = 0; i < brs.length; ++i) {

  if ((i + 1) % 5 == 0) {
    // create the new divider div and add the relative class to it
    var divider = document.createElement('div');
    divider.classList.add('divider');

    //insert the newly created div.divider
    brs[i].parentNode.insertBefore(divider, brs[i].nextSibling);
  }
}

jQuery: Take a look at jsFiddle 2

var brs = $('.beers');

brs.each(function(i) {
  if ((i + 1) % 5 == 0) {
    $('<div class="divider"></div>').insertAfter(brs[i]);
  }
});

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

Pass a notification to a separate function

Issue Looking for a way to send an 'event' to another function using jQuery. The goal is to prevent the removal of a table row before executing certain treatments, and then remove the row. I want to insert a modal window in between these actions ...

Determine which points fall within a specified radius by utilizing solely an array

I'm developing an application that utilizes Leaflet to store GPS coordinates of specific locations in a table format [lat,lng]. This functionality is only accessible from the back end. On the front end, I need to retrieve the current position and gen ...

Navigating and extracting nested JSON properties using JavaScript (React)

I am currently working with a nested JSON file that is being fetched through an API. The structure of the JSON file looks something like this: { "trees":{ "name":"a", "age":"9", "h ...

MongoDB not being updated

Currently, I am a student delving into the world of full-stack JavaScript development. One resource that I have found particularly helpful is a LinkedIn course where the project involves creating a blog with an "upvoting" feature. However, I have encounter ...

attempting to employ the method of copying by converting result into a JSON string

Currently, I am utilizing the browser console to scrape and organize content with JS. Below is the code snippet: This represents my result array var arr = [ "George\nPresident & Founder", "content", "Ronald\nCount ...

What are the steps to separate Bootstrap 5 from other frameworks?

Is there a way to apply bootstrap-5 styles only to a specific block or page? Can someone provide guidance on isolating bootstrap 5 either for the entire page or in a specific area? ...

What is the best way to print HTML code without having to write it multiple times?

I am working at a web application and i am doing some refactoring. Doing so, anyway, i was caught in a dilemma: i have some similar nor identical parts in my pages that i want to compress in just one in order to make some edits just once, since edits are ...

Utilizing unique symbols to dynamically add form elements to an HTML page with jQuery's append method

I am facing an issue with creating forms on my HTML page. Here is an example of how I am trying to do it: <form action="/tasks/<%= allTasks.e[0].id %>/delete" method="POST"> <button class="deleteTask">Delete</button> </f ...

encase a function with javascript

let myString = "I am creating a program."; //function to calculate number of letters const letterCount = (str) => str.length; //function to calculate number of words const wordCount = (str) => str.split(" ").length; //function ...

The XMLHttpRequest function successfully logs data in the console, but does not return the data within the function itself

I find it puzzling that the console.log statement at the end of the code snippet displays the data as expected, while the return optiondata line does not. function populate_selectbox() { var ajaxRequest; try { // Opera 8.0+, Firefox, S ...

Create a 3D vertical flip effect for images using CSS

Learning About HTML <div class="container"> <div class="wrapper"> <div class="im-fix"><img src="foo.jpg"></div> <div class="img-closed"><img src="foo-close.jpg"></div> <div class="img- ...

Arranging divs using inline-block display. How to adjust the heights consecutively?

After much searching and attempting, I am still unable to achieve a simple task. My goal is to apply display inline-block to some divs while aligning them in a row, similar to the image below: https://i.sstatic.net/iLhLS.png The issue arises when number ...

Tips for customizing the appearance of a jQuery sortable target list prior to dropping items

When using jquery sortable, I am able to customize a placeholder inside a connected list specified in the connectWith option to visualize where the content will be dropped. However, I am struggling to find a way to style the actual list that contains the p ...

Having trouble making SCSS mixins work with CSS variables in NextJS?

My current next.config.js setup looks like this: module.exports = (phase, {defaultConfig}) => { if ('sassOptions' in defaultConfig) { defaultConfig['sassOptions'] = { includePaths: ['./styles'], ...

Utilizing HTML5 to import content from text files

Currently, I am experiencing an issue with HTML 5. I am struggling to find a way to load data into a web page statically from locally saved files. So far, my only successful method has been using < input type="file" id="fileinput" / >, but I am inter ...

Configuring Vue.js watchers inside a for loop

Exploring the dynamic addition of watchers in Vue.js. The discrepancy between what is desired and what actually happens is demonstrated below in the commented section. As a casual coder, I believe my issue lies more in grasping JavaScript basics rather t ...

jquery to create a fading effect for individual list items

I have a group of items listed, and I would like them to smoothly fade out while the next one fades in seamlessly. Below is the code I've been working on: document.ready(function(){ var list_slideshow = $("#site_slideshow_inner_text"); ...

What is the reason for having a filled array containing data on currency exchange rates within an asynchronous function, while simultaneously having an empty array located outside of it? - React

After struggling with this programming issue for the past 5 days, I'm reaching out for help. The challenge I'm facing involves retrieving the rate of a specific currency between 1 and 50000 from an API. While I have successfully managed to obtai ...

A collaborative effort on Facebook, Twitter, and GooglePlus involves generating SCRIPT tags collectively

If you're familiar with the javascripts used by platforms like Facebook, Twitter, and Google Plus, you'll recognize them below. Here, I've simply organized them neatly together. How can I utilize jQuery to create the script tags and optimiz ...

Managing the order of rendering for sibling components in vue.jsUniquely controlling rendering order in

I have the following code snippet: <div> <compA /> <compB /> </div> How can I ensure that compA is rendered only after compB is rendered? The reason for this is that I have dependencies on certain elements in compA, and the s ...