Tips for Centering a div When Dynamically Adding Contents

Take a look at this image https://i.sstatic.net/NUwDQ.png

I utilized Bootstrap to align the divs and created only one div. The contents within this div are added dynamically from the admin side, then looped through. It's functioning properly.

However, you'll notice that only 6 contents are available here. So, 2 divs are aligned to the left. I wish for these divs to be centered on the page. If there are 7 or 5 contents, the second row of contents should also be in the center. How can I align these divs in the middle? Please assist me in solving this issue.

Below is my code:

<div class="col-sm-6 col-md-3">
        <div class="service-item hvr-grow wow fadeIn" data-wow-duration="500" data-wow-delay="100ms">
            <img src="{{ 'assets/img/icon-services.png' |theme }} ">
                <h4>{{ service['name'] }}</h4>
                <p>{{ str_limit(service['description'], 100) }}</p>
                <a href="{{ url('services') }}/{{ service['slug'] }}" class="read-more">Read More</a>
        </div>
    </div>

Thank you in advance.

Answer №1

Make sure to include display: inline for the child div and text-align: center for the parent div. Avoid using col-md from bootstrap as it contains the property float: left.

.parent {
  text-align: center;
}

.child {
  display: inline-block;
  width: 24%;
  border: solid 1px #123;
  height: 50px;
  margin: 0 auto !important;
}
<div class="parent" id="parent">
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
</div>

Answer №2

If you want to adjust the position of each div dynamically, consider using bootstrap to set an offset based on your desired layout. Alternatively, you can set the margin of the divs to auto for automatic alignment. Check out this resource for more information on centering columns with Twitter Bootstrap 3.

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

Why does my express POST request result in an empty req.body in Node.js?

After confirming that my data is being passed correctly and the db connection is successful, I am facing an issue with my ajax request. Even though the success callback returns the id, my data seems to not be passing through properly. When attempting to a ...

When utilizing ES6, my HTML elements do not have event listeners re-attached to them unless I refresh the page

So, I have a task where I am displaying a simple string on the screen. The goal is that when you click on any letter in the string, it should be removed from its current position and added to the end of the string. However, after clicking on a letter and u ...

Embracing the power of dynamic imports in Next.js 10 with SDK integration for

I attempted to dynamically import the TRTC SDK using Next.js 10: const TRTC = dynamic(() => import('trtc-js-sdk').then((module) => module.NamedExport), { ssr: false }); However, I encountered an error stating "TRTC.createClient is not a co ...

Sending objects as parameters to a class in JavaScript - an easy guide

Having trouble passing a parameter to the class for handling AJAX errors. The initial function is as follows: function GetLastChangePass(UserId) { var field = { id: UserId, } var fieldStringified = JSON.stringify(field) $.ajax({ ...

The filter designed for rearranging elements will not function

let wrap = document.querySelector(".wrap"); let temp = document.querySelector(".temp"); temp.addEventListener("click", (event) => { // grabs the first paragraph child element, which is working correctly console.log(wrap.children[0].firstElementChild ...

How can I utilize the mapping function on a promise received from fetch and display it on the page using React

As I'm using fetch to return a promise, everything is working fine. However, I am facing an issue while trying to map over the fetched data. When I check my console log, it shows "undefined." const dataPromise = fetch('http://api.tvmaze.com/sche ...

React hooks - The setState function fails to modify state attributes

I've implemented an event binding on the window object for scroll events. The event gets fired correctly every time I scroll, but I'm facing an issue with my setNavState function (which is actually my setState-function) not updating the state pro ...

When attempting to execute the "npm run prod" command, the terminal displays the error message "error:03000086:digital envelope routines::initialization error."

In my current project, which combines vue and laravel, I encountered an issue when trying to run the production command: npm run prod The error message that appeared was: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization ...

Protractor: Unable to reach variables within closure set in the parent function

I have a code snippet in one of my JS files that looks like this: // test/lib/UserHelper.js 'use strict'; var Firebase = require('firebase'); exports.createUser = function (email, password) { browser.executeAsyncScript(function (do ...

CSS is effective when styling table elements such as 'tr' and 'td', but encounters issues when trying to include 'th'

I have a variety of tables on my website, most of them without borders. However, I want to add borders to some of them. In my CSS, I am using a specific class for those tables: table { padding: 2px; border-collapse: collapse; table-layout: auto; te ...

Is the rotate() method in SVG supported on web browsers when passing in additional parameters like angle, centerX, and centerY similar to the CSS rotate

I have recently learned about a rotate transform that allows for rotating around a specified center point using the `rotate(angle, centerX, centerY)` method. However, I have noticed that this method does not seem to work when applied via CSS. Interestingl ...

Working with nested objects in a React functional component's state using TypeScript

In my React functional component state, I have a nested object that I can only access the first level of if I use the any type. export default function Detail() { const [user, setUser] = useState<any>({}); const { id } = useParams(); us ...

Discover the steps to capture the ajax initiation and completion events

In my application, I have numerous ajax requests. To display a loading symbol while these requests are in progress, I am utilizing jquery ajaxStart and ajaxStop methods. However, for some reason, they seem to not be functioning as expected. Despite searc ...

Is there a way to attach a canvas image to an email using VB.NET?

In my project, I have successfully converted an SVG to a canvas image using canvg, then converted it to a bytearray in vb.net on the client side. I saved the image to a folder on my server in order to attach it to an email: Protected Sub Button1_Clic ...

The React component fails to inherit any props that are passed to it when it is rendered using a logical operator

I'm facing an issue with a component that doesn't seem to receive any props when I use a logical operator in conjunction with it. Oddly enough, if I render the component without the conditional statement, everything works fine. But as soon as I a ...

Several examples of objects utilizing the identical function as the most recent instance

While working on a new feature for a Javascript library, I ran into an interesting issue. It seems that when a function of an object utilizes a closure and a promise together, all instances of the object end up using the most recently created version. This ...

What purpose does the 'shape' function serve within yup?

While many examples of Yup utilize the shape method, I have found the documentation to be somewhat unclear on why this approach is preferred and what exactly it accomplishes. Could someone clarify the distinction between a schema constructed with Yup.obje ...

Instructions on how to insert a hyperlink into the information within the generated div utilizing an API

Currently, I am fetching information from an API based on the user's input (zipcode). The data retrieved includes the name of the institution, address, and webpage. I've been trying to make the webpage link clickable by adding a hyperlink to the ...

Interval set does not refresh an integer

I'm struggling with a function that is supposed to show the number of milliseconds elapsed since Midnight on January 1st, 1970. I've been trying to use setInterval to update the integer every second or millisecond, but it doesn't seem to be ...

Navigating through the drupal module directory using JavaScript

Is there a way to retrieve the module path in Drupal 7 from which a .js file was loaded? Although JS is primarily a front-end language, is it possible that Drupal includes this information within the Drupal object? Essentially, I am trying to achieve so ...