Styling Alternating Rows with Left-Floated Elements in CSS

I'm in the process of revamping the layout of my blog using CSS3. Rather than continuing to utilize a table like I did before, I want to explore new design possibilities.

My blog is titled "Wall of Text," and its header features a unique brick-like pattern created by a repeating background image. Below the header are links to archived posts that also mimic the appearance of bricks from the wall of the header. While the first row looks perfect, I am encountering challenges when the links wrap onto the next row. In order to maintain the brick-like pattern, I believe the second row should have a left offset/margin/padding of 20px.

The arrow indicates where I desire the indentation.

Initially, I attempted to use the display: table-row container with the :nth-child(even) selector for styling. However, I found it difficult to position elements correctly, so I switched to using display: table. Unfortunately, the current setup results in the :nth-child(even) selecting every other brick instead of every other row.

If you'd like to take a look at my code populated with placeholder "links," you can find it here: jsfiddle.

Any suggestions on how I can achieve this desired layout?

Answer №1

The initial step involves identifying the starting point of new lines. Assuming all bricks are of the same width, you can ascertain the number of bricks per line by knowing the total width of the bricks and that of the container.

Code in Javascript

// calculating the width of the brick container
var cont_width = document.getElementsByClassName('bricks')[0].offsetWidth;

// summing up the widths of all the bricks 
var bricks_width = 0;
var bricks = document.getElementsByClassName('brick');

for (var i = 0; i < bricks.length; i++) {
    bricks_width += bricks[i].offsetWidth;
}

In the next step, some margin needs to be added (possibly negative) to the first element of every second line. In the code snippet above, we have all the brick elements stored in var bricks, which allows us to iterate through them again with this logic:

Javascript code

var bricksPerLine = Math.floor(bricks.length / (bricks_width / cont_width));
var bAlt = false;

for (var i = 0; i < bricks.length; i++) {
    if (i % bricksPerLine == 0) {
        if (!bAlt) {
            bAlt = true;
            bricks[i].style.marginLeft = '-20px'
        } else {
            bAlt = false;
        }
    }
}

JS-Fiddle


Note: For responsive websites, this code must be triggered on each resize event. It's evident that there are areas where the code can be further optimized.

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

Navigating websites with JQuery

I'm struggling to create basic website navigation using JQuery. My website has multiple .html files with different content, but I want to have a persistent page where the content loads into a specific div. Currently, my navigation works like this: ...

The content of the modal box is determined by the custom field

I need your help with displaying different content in a modal box using featherlight.js. The idea is simple: If there is an image, it should display the image. If not, it should show a SoundCloud URL iframe. But for some reason, it's not working as e ...

Double f span causing unusual behavior in Chrome browser

Why does the highlight focus on "ort" instead of "fort"? It appears this occurs when there are two f's. When I substitute f with other letters, like d, it shows correctly. Could this be a bug in Chrome? Chrome version is chrome83. add: It seems to be ...

Is there a way to display an element only when it is clicked on, and then hide it when other elements are clicked on?

Description: My webpage includes two buttons and two additional elements (div & section). When button 1 is clicked, the div element appears with a HotPink background-color. If button 1 is clicked again, the div element disappears. Similarly, button 2 revea ...

Manipulating class and element text within an anchor element using jQuery

Here is the HTML code that I am working with: $(document).ready(function() { $(document).on('click', '#btnVisible', function(e) { // Logic Here return false; }); }); <script src="https://ajax.googleapis.com/ajax/libs ...

Populate a form with data retrieved from a MySQL query result

One aspect of my project involves a specific interface called 'designation.php' that contains a form. The goal is for users to enter a 'designation code' (which serves as the primary key) and then click the 'update' button, pr ...

Struggling with resizing my card height in bootstrap

<div class="card border-dark bg-white text-dark" style="width: 400px; height: auto; margin :10px auto "> <div class="card-header"> <h3>Sign up for our Services</h3> </div& ...

Is there a way to ensure the browser always fetches the HTML and CSS files from the server instead of relying on the cache?

I'm currently in the process of building a website with Angular and JavaScript. However, every time I make updates to the site, the client is required to clear their cache in order to see the changes. Is there a way for me to seamlessly force the brow ...

Styling a dynamically-injected div using an AJAX request (xhrGet)

Hello everyone, currently I am using the code below to fetch updated content after receiving a "push" event from a server. The new content is then used to replace the existing div/content. However, I'm facing an issue where none of my styles from the ...

Modifying the CSS will not be reflected in the appearance

Currently, I am facing an issue on a website where I cannot make any changes to the CSS stylesheet. Whenever I attempt to modify a style, it appears to work temporarily but then reverts back to its original state once I release the mouse. It seems like the ...

Looking to include a tag in the top left corner of a product card?

Looking to create a unique tag for a card on my website to showcase a new product. My vision is to have an eye-catching design positioned in the top left corner of the card. Seeking assistance with crafting the CSS code for this specific element. Initial ...

Achieving functionality with dropdown menus in jQuery

I am facing an issue with a dropdown menu that works perfectly in jsFiddle during testing, but does not function as expected when I run it on my testing server. jsFiddle: http://jsfiddle.net/cyberjo50/39bu8/2/ HTML <!doctype html> <html> < ...

inadequate document object module problem

Upon loading a page, I perform some JQuery actions on it. However, when trying to execute the line: var div = $("<div class='modal'>").append(r); I encountered an error mentioning a Hierarchy issue. It made me question if there is imprope ...

Set a div to have both absolute positioning and sticky behavior

Looking to create a div ("profilemenu") that pops out on the right side of the page triggered by a button (I'll handle this part). I want it to have a sticky attribute, but positioning has been tricky. Using position: absolute works for proper placeme ...

Leveraging CSS Files with InertiaJS, Vue, and Laravel

I found a solution by using global CSS to remove the bootstrap button border on focus throughout all my Vue components. resources/css/app.css .btn:focus { box-shadow: none; } resources/views/app.blade.php <!DOCTYPE html> <html> <head ...

Is there a copyright concern regarding CSS?

There are countless websites that spark my creativity. If I am inspired by a particular design, CSS, or JavaScript on one of these sites, am I allowed to copy it to my local folder and use it? For instance, let's say I come across a website called xy ...

Create a stylish design with Bootstrap 3.0 featuring a full-width color background and compact columns perfectly centered on the

As I ventured into creating a business theme with stripes, akin to the one developed by W3Schools and accessible here, I encountered a particular challenge. The layout consisted of horizontal sections with varying background colors. My main concern was th ...

Refreshing a specific area on a webpage through the use of Ajax technology

I need to update a specific part of my webpage when a user clicks on the 'clear' button. I currently have some code that I borrowed from another answer I found on this site: $('.clear').click(function () { $.ajax({ url: "", ...

Sending the complete data from an HTML table to a web method

Is there a way to pass the data from a dynamically generated HTML table grid to a web method using jQuery AJAX? The table grid creates multiple rows on button click at runtime, and I need to send the entire table data. Please refer to the following snaps ...

Scripted AngularJS directive

Essentially, the directive I have defined as sample.js is: app.directive('myDirective', function() { return { restrict: 'E', scope: { info: '=' }, templateUrl: 'link-to-sam ...