Question

Here's the full screen result: http://jsfiddle.net/anik786/UYkSf/4/embedded/result/

Here's the HTML/CSS: http://jsfiddle.net/anik786/UYkSf/4/

Here's the HTML:

<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 the CSS:

* {margin: 0; padding: 0;}

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

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

The problem is that when the window size is at certain widths, there is too much space on the right hand side (try it out yourself with the full screen result by resizing the browser).

Therefore I'm trying to centre the container so that the gallery is always in the middle of the screen. I normally use:

margin: 0 auto;

However I can't use this because I don't know what the width of the container will be (as it depends on the window size).

Please help! Thanks in advance!

Was it helpful?

Solution

There are many ways to centre elements:

Margin way:

With a set width or display: inline-block; you can use:

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

text-align way:

You can add this to the parent:

text-align: center;

Absolute way:

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

or

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

The best way for you would be to remove the float on .pic and instead add display: inline-block. Then on the parent add text-align: center;

OTHER TIPS

You can use display: table to center an item that has not been defined a given width. Then use margin: 0 auto;

Example http://jsfiddle.net/LstNS/11/

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

You can also center using max-width

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

I assume the gallery would have a % width anyway in a responsive site.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top