Ensure that a div with fluid width remains consistently centered within another div

I have a bunch of boxes filled with content. The number of boxes in each row varies depending on the width of the browser window.

Is there a way to ensure that all the boxes are always horizontally centered on the page?

For guidance, you can check out this example: FIDDLE

HTML:

<body>
<div class="centered">
    <div class="segment">Content</div>
    <div class="segment">Content</div>
    <div class="segment">Content</div>
    <div class="segment">Content</div>
    <div class="segment">Content</div>
    <div class="segment"><Content</div>
    <div class="segment">Content</div>
    <div class="segment">Content</div>
    <div class="segment">Content</div>
    <div class="segment">Content</div>
    <div class="segment">Content</div>
</div>
</body>

CSS:

body {
    background-color:grey;
    margin:0px;
    padding:0px;
}
.centered {
    min-width:620px;
    max-width:1920px;
    margin-right:auto;
    margin-left:auto;
}
.segment {
    float:left;
    height:300px;
    width:300px;
    margin:5px;
    background-color:red;
}

I'm willing to consider JavaScript and jQuery solutions, but I'd prefer to utilize HTML and CSS if possible.

Answer №1

Give this a try

.centered {
    min-width:640px;
    max-width:1920px;
    margin-right:auto;
    margin-left:auto;
    display:inline-block;
    text-align:center;
}
.segment {
    display:inline-block;
    height:300px;
    width:300px;
    margin:5px;
    background-color:red;
}

Check out the DEMO here

Answer №2

i engage in this activity

1 -

.centered { display:block; text-align:center; }

2 -

.segment

eliminate floating property

incorporate display:inline-block

enjoy the process

Answer №3

Resolving your issue with just HTML/CSS may be challenging, but a simple JS solution is provided below.

<body>
    <div class="centered">
        <span id="segmentList">
            <div class="segment">Content</div>
            <div class="segment">Content</div>
            <div class="segment">Content</div>
            <div class="segment">Content</div>
            <div class="segment">Content</div>
            <div class="segment">Content</div>
            <div class="segment">Content</div>
            <div class="segment">Content</div>
            <div class="segment">Content</div>
            <div class="segment">Content</div>
            <div class="segment">Content</div>
        </span>
    </div>
</body>

<script type="text/javascript">
    $('div.centered').width($('#segmentList').width());
<script>

Demo

Answer №4

To ensure proper alignment, adjust the width of the container based on different screen sizes:

http://jsfiddle.net/y6JpY/

@media screen { .centered { width: 620px } }
@media screen and (min-width: 930px) { .centered { width: 930px } }
@media screen and (min-width: 1240px) { .centered { width: 1240px } }
@media screen and (min-width: 1550px) { .centered { width: 1550px } }
@media screen and (min-width: 1860px) { .centered { width: 1860px } }

These numbers are multiples of 310 (300 + 5 pixels margin on each side).

This approach also prevents orphaned tiles from being centered at the end.

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

"Feeling puzzled by the intricacies of the Jquery Timer

I am currently using the jQuery Timer plugin from to dynamically generate documents every 5 seconds with pause and resume functionality. Below is my script: $(function() { $('.handler').load("../Pages/csFetchCustomer.ashx?"); ...

Implementing multiple modules within a shared parent route in Angular

Currently, I am seeking a method to load multiple modules under the same path in Angular. Let's say I have three modules: AModule, BModule, and CModule, each with its own RouterModule.forChild call. My goal is to combine these modules under the route ...

"Combining variables in programming: A step-by-step guide with a sample

When I press the first button, I expect to see random numbers displayed: 817 754 692 Pressing the second button '123:123' should show the numbers like this: 817:817 754:754 However, the output I am getting is: 817 754 :817 754 How can I com ...

Issue: A React component went into suspension during the rendering process, however, no alternative UI was designated

I'm currently experimenting with the code found at https://github.com/adarshpastakia/ant-extensions/tree/master/modules/searchbar Although I followed the tutorial instructions, I encountered an error. Could it be that the library is malfunctioning? I ...

Tips for positioning the title of a card in Bootstrap-Vue

I'm currently working with the <b-card> component from bootstrap-vue and encountering an issue where I am unable to center align the title property. Does anyone have a solution for this problem? Below you can find the structure of my card, which ...

Arranging search findings based on relevance using javascript

I'm developing a personalized search feature. Currently, when I type "The R," the search results list starts with The Fellowship of the Ring because the phrase "the ring" is in its .text property. However, I want The Return of the King to appear first ...

Arranging text and images strategically

I am trying to position an image and text within separate containers using div. The desired layout is to have the img floated left and the text centered on the page, but I am having trouble achieving this. Each element has its own div. Can you provide as ...

Creating a fixed navigation bar that stays at the top of the page when scrolling

I am trying to create a navigation bar similar to the one seen on W3School's website. I would like the navigation bar to overlap the header when scrolling down, and for the header to appear above the nav bar when scrolling back to the top. Despite m ...

Get the desired text following the second <br> tag using jQuery

I am trying to identify a specific string that comes after the second occurrence of <br> tag and then check if this string contains any numbers. If there are no numbers present, I want an alert to be shown. The code for performing this action is func ...

Cross-Origin Resource Sharing - redirecting to the page that is being retrieved by a subsequent GET request

My web page makes AJAX requests using JQuery $.ajax to load content. However, if the user session expires, re-authentication is required. When a user is not authenticated, two GET requests are sent to the website: one with the requested URL in the AJAX (o ...

Tips on extracting the value from the chosen option in 2 separate rows with identical IDs

While looping through my table, each row is identified by the id="batchNo". I am trying to retrieve the selected value of each select option in every row. Although I attempted to achieve this with the provided code snippet, it only retrieves the selected ...

The ajv-based middy validator does not adhere to the specified date and time format

When it comes to validation, I rely on middy as my go-to package, which is powered by ajv. Below is an example of how I set up the JSON schema: serviceDate: { type: 'string', format: 'date-time' }, The structure o ...

JavaScript: Harnessing the power of scripts to handle dynamically loaded data via AJAX

I am currently working on a webpage where I need to display various events using AJAX and PHP. One requirement is that when a user clicks on the "view event" link at the bottom of each event, a modal window should pop up. To achieve this functionality, I h ...

Express 4 app.use not functioning properly

My backend setup is fairly straightforward with a few routes. I prefer to keep the route logic separate from the server.js file, but for some reason, when I make a POST request to the route, it returns a 404 error. In the server.js file: // Import necess ...

Disable the off-canvas sidebar when a link is clicked in Jasny Bootstrap

Working on a website located at When viewing the site on mobile devices ( < 768px ), I am struggling with getting the off-canvas navigation to automatically close after clicking on one of its links. Any assistance would be greatly appreciated as I&apos ...

Getting the jQuery selector result into the routevalues object for @Ajax.ActionLink: How can it be done?

Here is the code for an @Ajax.ActionLink I am working with: @Ajax.ActionLink("Assign Ownership", "AssignOwnership", new { techLogCode = Model.TechLog.Code, salesRepId ...

AngularJS to validate image dimensions (width and height) on upload

Hello, I am new to working with Angular JS. I have been experimenting with a login form that includes a file upload field for the user picture. The input field code looks like this: <input type="file" file-model="userPic"/> When I submit the form i ...

Tips on converting a Java regular expression to JavaScript regular expression

Can someone assist me in translating the Java Regex code below to JavaScript Regex? (\\\p{Upper}{2})(\\\d{2})([\\\p{Upper}\\\p{Digit}]{1,30}+) I attempted using the following JavaScript Regex: ...

Locate all elements in an array that contain a particular value for a specific key using Javascript

In my JavaScript data, I have two arrays: ARRAY ONE: [ TextRow { v_id: 3000 }, TextRow { v_id: 3001 }, TextRow { v_id: 3002 } ] ARRAY TWO: [ TextRow { s_id: 'S001', v_id: 3000, type: 'control' }, TextRow { ...

I am seeking assistance with optimizing my website for mobile use as I have exhausted all recommendations I could find without success

After years of working with HTML, I am now faced with the challenge of making my website mobile-friendly. Despite trying various suggestions found online, the mobile version of my site is still not functioning properly. Currently, only about 6 pages are op ...