Creating a Centered Masonry Layout with CSS

Recently, I designed a masonry layout with CSS grid.

I had a specific requirement for this layout - it needed to have a maximum of 8 columns and also be responsive based on the screen size.

Initially, everything worked perfectly until the number of items in my "masonry" exceeded or fell below 8. When the count was less than 8, I wanted the columns to be centered within the "masonry".

HTML

<body>
    <div class="masonry">
        <p class="subheading-text">Automobiles</p>
            <img class="content-img" src="https://www.otgads.com/site_contents/image_Ad/235/1672659803.jpeg">
        
        <img class="content-img" src="https://www.otgads.com/site_contents/image_Ad/233/download (2).jpeg">
        
            <p class="subheading-text">Badhai</p>
            <img class="content-img" src="https://www.otgads.com/site_contents/image_Ad/223/advertisement(2).jpeg">
        
        
            <p class="content-text"><strong>Lorem</strong> Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop </p> 
        
            <p class="subheading-text">Business</p>
            <p class="content-text"><strong>WANTED</strong> Investor/Partner Rs.3.5 Cr for our Packaging Material mfg Unit Nr. Mumbai 7021629703 9821009496</p> 
        
            <p class="subheading-text"gt;Education</p>
            <p class="content-text"><strong>Lorem</strong> Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and</p> 
       
    </div>
</body>

CSS

body {
  margin: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.masonry {
  --masonry-gap: 15px;
  --masonry-brick-width: 200px;
  column-gap: var(--masonry-gap);
  column-fill: initial;
  column-width: var(--masonry-brick-width);
  max-width: 1740px;
}

.masonry > * {
  break-inside: avoid;
  margin-bottom: var(--masonry-gap);
}

@supports (grid-template-rows: masonry) {
  .masonry {
    display: grid;
    gap: var(--masonry-gap);
    grid-template-rows: masonry;
    grid-template-columns: repeat(
      auto-fill,
      minmax(var(--masonry-brick-width), 1fr)
    );
    align-tracks: stretch;
  }

  .masonry > * {
    margin-bottom: initial;
  }
}


.masonry {
  padding: 8px;
}

.content-text {
  padding: 10px;
  margin: 0px;
  border: 1px solid black;
  border-radius: 5px;
  transition: 0.15s ease-in-out;
}

.content-text:hover {
  background-color: antiquewhite;
  box-shadow: rgba(0, 0, 0, 0.22) 0px 19px 43px;
  transform: translate3d(0px, -1px, 0px);
}
.heading-text {
  margin: 0px;
  margin-bottom: 10px;
  padding: 10px;
  text-align: center;
  background-color: #ca4040;
  color: white;
  border-radius: 5px;
}

.subheading-text {
  margin: 0px;
  margin-bottom: 10px;
  padding: 10px;
  text-align: center;
  color: #404eca;
  border: 3px solid #404eca;
  border-radius: 5px;
}

.content-img {
  width: 100%;
  transition: 0.15s ease-in-out;
}

.content-img:hover {
  box-shadow: rgba(0, 0, 0, 0.22) 0px 19px 43px;
  transform: translate3d(0px, -1px, 0px);
}

If you can provide any assistance on how to solve the alignment issue within the 'masonry' container, it would be greatly appreciated.

I've tried various methods to center the contents inside the 'masonry' div, especially when the brick count falls below 8, but they always end up being left-aligned due to the fixed max-width set at 1740px for the 'masonry' div.

Answer №1

.layout {
  --layout-gap: 10px;
  --layout-brick-width: 180px;
  column-gap: var(--layout-gap);
  column-fill: initial;
  column-width: var(--layout-brick-width);
  max-width: 1600px;
  display: grid;
  gap: var(--layout-gap);
  grid-template-rows: layout;
  grid-template-columns: repeat(auto-fill, minmax(var(--layout-brick-width), 1fr));
  align-items: center; /* included for column alignment */
  align-tracks: stretch;
}

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

Executing a Python script within an ASP.NET application upon loading

I have a python script that scrapes a webpage for currency conversion. I successfully used this script in a previous php project and now need to adapt it for use in asp.net. In the past, I executed the python script using JavaScript by loading it on the h ...

Updating the status of a work item using the PATCH method in the DevOps REST API is currently not working

Currently, I am utilizing the DevOps restapi to retrieve certain information. The POST method is functioning perfectly for me. However, when attempting to update the status of my work item using the PATCH method, it does not seem to be working and no er ...

What is the best way to showcase images in a carousel using an image URL?

I am struggling to populate images in a carousel using image URLs from JSON data. Although I attempted to use the attr() method in jQuery to set attributes, I have not been able to achieve the desired outcome. Below is the code snippet in question: <di ...

Ways to fix: Encountering an Unexpected token < in JSON at position 0

Hey there! I've just started dipping my toes into the MEAN stack. I'm currently using Angular to connect to an api.js file, which in turn connects to my mongodb database. However, I've come across this error: ERROR SyntaxError: Unexpected t ...

What is the ideal amount of HTML code to include in an Angular controller?

What are the implications of storing long paragraphs in controllers? For instance, if you have to display multiple lengthy paragraphs using ng-repeat, you may create a data structure like this within your controller: $scope.paragraphs['300 word para ...

Error: Cross-origin request prevented in Chrome due to XMLHttpRequest loading issue

It seems there is a bug specific to Chrome, as this code works without issue in all other browsers. Here's the snippet of code causing the problem: $(function() { $('#content').load('home.html' + '#container').hide( ...

Include a hyperlink beside the title of a section

drupal block heading I want to include a clickable link beside the header of this block that directs users to more news. Initially, I tried using CSS pseudo ::after to append text and a logo. However, I encountered difficulty in adding a clickable link t ...

Overlapping body content due to Bootstrap 4 navbar menu design

I've just kicked off a fresh website using bootstrap 4, but already facing hurdles right from the start. The navbar menu seems to be encroaching on some part of the body content, and I'm completely at sea. Attached is a terrible draft where you ...

Unable to deploy Azure App Service due to difficulties installing node modules

My Azure Node.js App Service was created using a tutorial and further customization. The app is contained within one file: var http = require("http"); //var mongoClient = require("mongodb").MongoClient; // !!!THIS LINE!!! var server = http.createServer(f ...

retrieve a string value from a function within a ReactJS component

I am facing an issue with returning a string from a function. Here is the function I am using: const getImage = (name) => { const imageRef = ref(storage, name); getDownloadURL(imageRef).then((url) => { return url; }); }; Even tho ...

Should you consider using the Singleton pattern in Node.js applications?

After stumbling upon this specific piece discussing the creation of a singleton in Node.js, it got me thinking. The require functionality according to the official documentation states that: Modules are cached after the first time they are loaded. Multi ...

Troubleshooting issue with Calendar styling in Bootstrap and SimpleCalendar Rails integration

I am having trouble applying styling to my SimpleCalendar in Rails, using the gem. When I render it, this is what I see: https://i.sstatic.net/kJi7m.png Here is the CSS provided by https://github.com/excid3/simple_calendar: .simple-calendar { table { ...

Merge together JQuery variables

I want to assign a unique number to each JavaScript variable and jQuery element in my code. Take a look at the snippet below: $("#insert1").click(function(){ var collegeId1=$("#collegeId1").val(); $.post('insert.php', {collegeId: colle ...

JavaScript code for styling changes is not functioning as expected

Check out this code snippet: var moving_nav = document.getElementById("moving_nav"); var logo = document.getElementById("logo"); setInterval(function(){ var scrolled = window.pageYOffset || document.documentElement.scrollTop; if (scrolled >= ...

When using firebase.firestore(), the data displayed is completely different and does not match the content of my actual database documents

I am trying to fetch data from firebase firestore using the following code: let db = firebase.firestore(); let locations = db.collection("location"); console.log("locations", locations); However, the logged data is coming back strange and not showing the ...

Unidentified function error triggered by jQuery when clicked

Having trouble accessing a function defined by my colleague for a click event. The code snippet provided below is causing issues, any ideas on what could be wrong? function Start(data) { this.move= function() { .... }; $('.button').click( ...

Exploring ways to increase the width of rows in Bootstrap 4

Is there a way to make a row expand to 100% of its containing div in Bootstrap 4? I've tried using w-100 and d-inline-block but neither seems to work. Any help would be appreciated. CODEPEN .container { width: 90%; border: 1px solid black; h ...

Utilize Vue Fullcalendar's eventRender feature to seamlessly incorporate Vue components into your

I am utilizing the fullcalendar.io vue extension. I would like to customize event rendering in order to add actions, but the event callback only contains JavaScript elements. Is there a way to inject a vue component into it? <FullCalendar ref="fu ...

Material-UI: Eliminating linkOperator functionality in data-grid

Is there a way to completely eliminate the linkOperator UI from the filter panel? I managed to move pagination to the top of the table using Material-UI, but can I achieve the same for the "Operators" menu programmatically? ".MuiDataGridFilterForm-linkOpe ...

Spacing before input text is found to be unnecessary and can be removed

Hello there, I've encountered a slight issue with a text input field that has border radius. The first character typed seems to protrude slightly outside the input field due to the border radius. Is there a way to add some extra whitespace before the ...