Reputation: 3131
I know this question has been asked many times before, but none of the answers have worked for me. I am coding in HTML5 and CSS 3.0. I am trying to center a div tag in a page, which contains three thumbnails that link to other pictures. I want the pictures to sit next to each other, with a margin of 0 (so they'll touch each other). Here is the html code I have:
<div id="main">
<h1>hello</h1>
<div id="gallery">
<a class="trigger" href="images/fulls/01.jpg">
<img class="thumb" src="images/thumbs/01.jpg">
</a>
<a class="trigger" href="images/fulls/02.jpg">
<img class="thumb" src="images/thumbs/02.jpg">
</a>
<a class="trigger" href="images/fulls/03.jpg">
<img class="thumb" src="images/thumbs/03.jpg">
</a>
</div>
</div>
The CSS:
body {
font-family: arial;
background: darkgray;
color:white;
text-shadow:1px 1px 3px black;
text-align: center;
}
#gallery {
text-align: center;
width: 462px;
}
.trigger {
position: relative;
display: block;
float: left;
}
This results in the title "hello" being centered, and the three thumbnails stuck to the very left. They have no distance between them, and aligned in a row as I expected, but I cannot get them to center.
Upvotes: 1
Views: 111
Reputation: 46208
Use margin: 0 auto
to automatically distribute the margins on the left and right of the block-level element:
#gallery {
text-align: center;
width: 462px;
margin: 0 auto;
}
Of course it can be margin: <length> auto
if you wish to have a margin on the top/bottom as well, just ensure that margin-left
and margin-right
are set to auto
.
This will center the div
in its parent (whether that be body
or something else), but you are floating your anchors left. Floating automatically makes the elements block-level, so text-align
will not apply to them (rather their children, if any, will inherit the property).
Remove the display and float properties of the .trigger
class:
.trigger {
position: relative;
}
I'm not sure if you need relative positioning for something else or why it's there, but I've left it there for now in case you do need it for something else.
If the images are not touching, it is because there is a space somewhere before or after the img
element. Ensure that the img
tag is between the a
tags with no space before or after, nor any tabs or newlines. More about this problem: Fighting the Space Between Inline Block Elements
See jsFiddle demo.
Upvotes: 3
Reputation: 3221
i am thinking that you should try something like
#gallery {
text-align: center;
width: auto;
margin: 0 auto;
}
Upvotes: 0
Reputation: 20189
You need to remove float:left
from your images and use display: inline-block;
then add margin: 0 auto;
to your #gallery
Demo: http://jsfiddle.net/Dc5Af/
Upvotes: 3