What is the best way to center a div horizontally when the width is unknown?

Check out the full screen result here: http://jsfiddle.net/anik786/UYkSf/4/embedded/result/

Here's where you can find the HTML/CSS: http://jsfiddle.net/anik786/UYkSf/4/

This is the HTML code:

<div class="gallery_container">
<div class="pic">
    <img src="http://petapixel.com/assets/uploads/2012/02/sample1_mini.jpg" />
</div>
<div class="pic">
  <img src="http://www.ndaccess.com/Sample/Images/Image1.jpg" />
</div>
<div class="pic">
    <img src="http://petapixel.com/assets/uploads/2012/02/sample1_mini.jpg" />
</div>
<div class="pic">
  <img src="http://www.ndaccess.com/Sample/Images/Image1.jpg" />
</div>
<div class="pic">
    <img src="http://petapixel.com/assets/uploads/2012/02/sample1_mini.jpg" />
</div>
<div class="pic">
  <img src="http://www.ndaccess.com/Sample/Images/Image1.jpg" />
</div>

And this is the CSS:

* {margin: 0; padding: 0;}

body {background: black;font-family: arial;}
.gallery_container{
 /* Add your styles to center the container on the page */
}
.pic {
 height: 300px;
width: 300px;
overflow: hidden;
margin: 20px;
border: 10px solid white;
float: left;
}

.pic img{ 
height: 300px;
width: 300px; 
}

The issue arises when the window size reaches certain widths, creating too much space on the right side (you can test this with the full screen result by resizing the browser).

To tackle this problem, I am attempting to centralize the container so that the gallery remains in the middle of the screen at all times. Typically, I would use:

margin: 0 auto;

However, this approach doesn't work since I don't know the exact width of the container (as it relies on the window size).

I would appreciate any assistance! Thank you in advance!

Answer №1

There are several methods to center elements:

Margin technique:

If you have a specified width or use display: inline-block;, you can utilize:

margin-left: auto;
margin-right: auto;

text-align method:

You can apply this to the parent element:

text-align: center;

Absolute positioning approach:

position: absolute;
left: 50%;
margin-left: width/2;

or

position: absolute;
left: 50%;
transform: translate(0, -50%);

The most effective solution would involve removing the float from .pic and replacing it with display: inline-block. Then, on the parent element, include text-align: center;

Answer №2

If you have an element without a specified width, you can center it by using the CSS property display: table combined with margin: 0 auto;

Here is an example on how to achieve this: http://example.com

div {
    margin: 0 auto;
    display: table;
}

Answer №3

Another option for centering is to utilize max-width property

max-width: 80%;
margin: 0 auto;

It's safe to assume that the gallery will have a percentage-based width in a responsive design.

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

Particles.js fails to persist as I scroll down the HTML page

After creating a website page, I incorporated Particles.js for the background. However, when I scroll down, the particles seem to be confined to the initial corner of the screen and do not continue downward. Here are my current particle settings: #particl ...

Which is more accessible: a disabled textbox or a div with role="textbox"?

Imagine I have a form in which one of the fields (name) is always disabled. When it comes to accessibility, would it be more effective to use an input <label> Name <input role="textbox" aria-readonly="true" value="Joe Shmoe" /> < ...

Is your CSS failing to display images properly?

I recently launched my website, www.alphenweer.nl, and everything seems to be working fine except for the images in the template. Despite being on the correct URL, the images fail to load when the website is accessed. You can test it out here. Can someone ...

Using the window.prompt function to send information to specific fields in a MySQL database is not functioning correctly. I am looking for assistance with this issue

Currently, I am attempting to send some data to a server that is MySQL-based. After running the code below, it seems like there are no errors showing up in the console. Can you please review this code and let me know if you spot any issues? I would really ...

Is there a way to easily duplicate this and add a navigation bar and logo to every page?

Why is it that when I copy and paste this code into any .html document, it only runs correctly on the resources tab? The logo is only showing up on the resources page, even though it's using the same css stylesheet and html structure. <div class=" ...

Ensuring a fixed table with vertical scrolling only, no horizontal scrolling, while scrolling in either direction

I'm working with an HTML fixed design that contains a center-aligned table with extensive data scrollable both vertically and horizontally. To address the issue of keeping column headers visible when scrolling vertically, I used jQuery's clone() ...

Heroku NodeJS - Page Not Found: Error 404

I recently set up a Heroku server with BootBot running on it, but I'm facing challenges while trying to render an HTML page from it. Here is what I have in my code: var app = express(); var path = require('path'); app.use(express.static(pat ...

Concealing a child component when hovering over its parent element with styled-components

I have a react component structured like this - const MyComponent = () => ( <ContainerSection> <DeleteButtonContainer> <Button theme="plain" autoWidth onClick={() = ...

The functionality of the AJAX Script is failing to load properly on mobile devices

Currently, I am undertaking a project that involves ESP32 Arduino programming to create a webpage where users can interact with buttons to activate relays. Additionally, I have implemented a slider using a short script. This project is inspired by the ESP3 ...

Fixing the background transition issue on Safari is a common problem that many users encounter

My background image, which is overlaid with a gradient, does not show up on Safari (although it works perfectly on Chrome). body{ background:linear-gradient(rgba(0, 0, 0, 0.95),rgb(0, 0, 0, 0.95)),url("https://www.w3schools.com/cssref/img_tree.gif" ...

Limitations on Embedding Videos with YouTube Data API

I have been using the Youtube Data API to search for videos, but I am encountering an issue with restricted content appearing in the results. Specifically, music videos from Vevo are showing up even though I only want videos that can be embedded or placed ...

Showcase JSON data within a designated div

As someone new to HTML, JavaScript and Vue, I'm unsure if my issue is specific to Vue or can be resolved with some JavaScript magic. I have a Node.js based service with a UI built in Vue.js. The page content is generated from a markdown editor which ...

Tips for adding jQuery UI styling to elements generated dynamically

I have a challenge with generating text fields using jquery while applying jquery ui styling to the form. The issue is that the dynamically created elements do not inherit the css styles from jquery ui: let index = 0; $('#btn_generate').on(& ...

Center the image within a Grid item using Material UI's alignment feature

I am currently utilizing the Grid component from Material UI. I'm facing an issue where the image inside a Grid item is aligned to the left instead of being centered. <Grid container direction="row" justify="center" alignIte ...

Can a single div have three different border-bottom styles?

Can three border-bottom styles be applied to a single div element? This is the desired appearance: ...

Alignment of UI Divs with CSS Bootstrap and HTML

I am facing an issue with two divs in my UI. One div has a label, and the other contains a file selector. Currently, they are stacked vertically instead of being side by side. https://i.stack.imgur.com/fIz03.png How can I align these divs horizontally wit ...

How to shift an image to the right side of the navbar

Is it possible to change the position of an image within a navbar from left to right? I have tried using the float property but it doesn't seem to work. .logo-img{ float: right; margin: 0px 15px 15px 0px; } <a class="navbar-brand logo-img" ...

Rearrange the li elements within multiple ul lists using JavaScript

Is there a way to reorder multiple ul-lists on my website using JavaScript? An example of the lists may be as follows: $(document).ready(function() { var ul = $('ul.filelist'); for (let u = 0; u < ul.length; u++) { const element = ul[ ...

Exploring GLTF models with Threejs - just a click away!

I am currently developing a project in three.js where I aim to load a GLTF file consisting of geometric shapes. My goal is to extract information, specifically the name, of the shapes that are clicked within the GLTF file. At this stage, I am using console ...

Aligning thumbnail images in a jQuery Mobile listview

Hey, I recently added a list view that includes thumbnails. I used the following code: <ul data-role="listview" data-inset="false" data-theme="a" data-dividertheme="d> <li><a href="image.php?imgid=2"> <img src="../images/comma. ...