Arranging a layout of interactive div elements

I am currently working on setting up a responsive grid within my HTML code. The content is contained within a bootstrap .container and consists of multiple div elements. The number of these divs can vary based on external factors, and I need the layout to adapt accordingly. If there are an even number of divs, I want them to be arranged in a 2xn grid format. However, if there's an odd number of divs, I still want a grid layout but with the last div centered in its own block.

HTML

<div class="container">
    <div class="targetcontainer">
    <div class="target">
        <p>content goes here man</p>
    </div>
    <div class="target">
        <p>content goes here man</p>
    </div>
    <div class="target">
        <p>content goes here man</p>
    </div>
    <div class="target">
        <p>content goes here man</p>
    </div>
    <div class="target">
        <p>content goes here man</p>
    </div>
    </div>
</div>

CSS

.target {
  display: inline-block;
  width: 47%;
  min-width: 400px;
  height: 265px;
  margin: 10px 10px;
  padding: 2%;
  vertical-align: top;
  background: #fff;
  border: 1px solid #ebebeb;
  text-decoration: none;
  -webkit-transition: all 0.2s;
  -moz-transition: all 0.2s;
  -o-transition: all 0.2s;
  -ms-transition: all 0.2s;
  transition: all 0.2s;
  border-bottom: 3px solid transparent;
  cursor: pointer;
}

JS

function addClassToLastElement() {
  $('.target').each(function(index, element) {
    if ($(this).is(":last-child") && index % 2 == 0) {
      $(this).css('display', 'block')
      $(this).css('margin', '0 auto')
    }
  })
}

addClassToLastElement()

In my jQuery script, I check for the presence of an odd number of elements and apply specific styling to center the last div accordingly. You can view this functionality here (ensure that the screen size is relatively large).

However, an issue arises when the screen is resized. As the divs stack on top of each other, they don't center consistently except for the last one. Ideally, all the divs should align in the middle of the screen as they stack vertically. Is there a way to achieve this without relying on Bootstrap or using jQuery's .resize() function? My goal is to use only one Bootstrap element, specifically the .container.

Answer №1

To center all .target divs, add text-align: center to the parent container.

UPDATE:

/* Parent container styling */
.container{
    text-align: center;
}

/* Override for inner elements */
.container *{
    text-align: left;
}

UPDATE 2: (including a second container)

Visit this link for more information.

Answer №2

When creating a responsive design, one alternative is to utilize media queries. If the window width drops below 820px, consider applying margins to specific elements.

@media screen and (max-width: 820px) {
    .element {
        display: block;
        margin: 0 auto;
    }
}

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

What could be the reason for the next.js Script tag not loading the third-party script when using the beforeInteractive strategy?

I have been trying to understand how the next.js Script tag with the beforeInteractive strategy works. I am currently testing it with lodash, but I keep encountering a ReferenceError: _ is not defined. I was under the impression that when a script is loade ...

Add another condition to the current JavaScript rule

http://jsfiddle.net/e8B9j/2/ HTML <div class="box" style="width:700px">This is a sentence</div> <div class="box" style="width:600px">This is a sentence</div> <div class="box" style="width:500px">This is a sentence</div> ...

Query the number of Firebase instances using the firebase.appCount property in Firebase v

When setting up Firebase in my React applications, I typically initialize it as follows: if (firebase.apps.length < 1) { firebase.initializeApp(firebaseConfig); // Additional initialization for other Firebase products } This method was working flaw ...

Navigating through directories in an HTML file

In my directory, the folders are named in uppercase letters and have the following structure: ONLINESHOP |-- index.html |-- COMPONENTS |-- CONFIG |-- TEMPLATES |-- CSS |-- main-style.css |-- CONTROLLERS |-- MODE ...

What is the best way to make the first value of a text box non-editable in React JS

I am working on creating a text box field to generate a country code. The requirement is to have the first letter as a "+" symbol and make it a non-editable field for that symbol. _handlePhoneNumber(e) { var curState = {}; var valueLength = e.ta ...

What is the best way to adjust image size based on different screen sizes while ensuring the buttons at the top remain responsive

How can I make the image and image select and delete buttons responsive? I am looking to eliminate the gap after the delete button. Any suggestions are welcomed. <div class="container mt-0"> <div class="row"> ...

What is the best way to preserve an apostrophe within a variable in JavaScript without it being replaced?

How can I send the value of NewText in its original form from .cs code using an ajax call? **var NewText ="D'souza";** $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: " ...

Arrange documents within gulp-inject index function

I have encountered an Angular error due to the sorting of my files, so I am attempting to organize them properly. This is the content of my Gulp file: var gulp = require('gulp'); var angularFilesort = require('gulp-angular-filesort'); ...

Dynamic transition when selecting a navigation bar link in Bootstrap

Check out my website here: On my webpage, I have 3 navigation links which are: Who We Are What We Do Contact Us I have set up the "a href" tag to link to each section of the page when clicked. My query is, how can I create a sliding effect when clicki ...

A numeric input area that only accepts decimal numbers, with the ability to delete and use the back

I have successfully implemented a code for decimal numbers with only two digits after the decimal point. Now, I am looking to enhance the code in the following ways: Allow users to use backspace and delete keys. Create a dynamic code that does not rely o ...

An issue arises when attempting to integrate ajax with colorbox

I am currently facing an issue with a WordPress plugin designed for playing videos. It seems that the developer who created it is no longer available, and now the play video button has stopped working. Upon further investigation using Firebug, I noticed ...

Phonegap and the Importance of HTTP Requests

Having an unusual issue with Phonegap where my XMLHttpRequests are firing twice. Currently, I am working on an app that involves using XMLHttpRequests to generate a dynamic list of events for users to choose from. In addition to this, I am utilizing jQuery ...

unable to exit pointer lock controls in three.js

My code successfully locks the cursor, but I am struggling to unlock it when running a function. Here is my code: var element = document.body; var controls; var instructions = document.getElementById( 'start' ); var havePointerLock = 'poin ...

React Context Matters: Troubles Unleashed

I've been facing some difficulties with passing a value from one file to another. The problem seems to be related to implementing context, but I can't seem to figure out where I went wrong! import React from 'react' const Mycontext = ...

Running JavaScript in selenium and obtaining the result

I'm currently utilizing JavaScript with Selenium WebDriver. Here is a snippet of my code: let return_value = driver.execute_script(script) However, I am unsure how to retrieve the value from my script. const token = await grecaptcha.enterprise.exec ...

Is the error log susceptible to cross-site scripting attacks?

Recently, I came across an error logged at window.onerror by one of my users: {"message":"\"nativka already initialized\"","file":"https://staticcf0.ntvk1.ru/nvv.js","line":"12","fileName":"https://staticcf0.ntvk1.ru/nvv.js","lineNumber":"12"} ...

Steps for constructing an object containing an array of nested objects

I've been working on this problem for some time now, and it's starting to feel like a messy situation that just won't come together. I'm trying to recreate an object with 5 properties and a nested array of objects, but so far, it's ...

Showing off the latest products at the top of the list

Typically, when utilizing ngFor, the most recent item is displayed underneath the initial element. For instance, a list containing: [Apple, Orange, Banana] If we use ngFor to display this list: Apple Orange Banana I am interested in learning a method t ...

React incorrectly assigns index to Child when utilizing React.memo

Encountering an issue in my project that is too large to post all the code, so here's a summary. The parent component uses useReducer to manage state and returns a mapping of this state. Each child needs to receive both the value and index from the ma ...

Transmitting Various Static Files via Express Router

I am currently utilizing the Express router to serve static .html files based on the URL specified in router.get. For example, this code snippet sends the homepage: router.get('/', function(req, res, next) { res.sendFile('index.html&ap ...