tags:

views:

355

answers:

4

Hi,

I (absolute beginner) would like to put an image into a box with a little margin around. I tried with padding and so, didn't work. Then I tried this:

<div style="border:1px solid #CC6699; width:11em; height:5.5em;">
    <img style="align:center; width:10em; height:5em;" src="path">
</div>

But instead the image gets stuck in the upper left corner.

+2  A: 

Couple of ways to do this:

My usual is to set a background image instead.

In your css:

div#img_container {
    background: url(images/myImage.png) center center
}

In your html:

<div id="img_container"></div>

Or to just put some padding around it in your CSS

img#myImage {
    padding: 20px;
}

and the HTML

<img id="myImage" src="images/myImage.png" />
rpflo
The first suggestion is only appropriate if he's talking about a decorative image of some sort; if it's an image that's actually part of the content, don't do this. The second would probably be better done with margins.
Bobby Jack
Went with padding cause he said he tried that. But you're right, on both accounts.
rpflo
+1  A: 

CSS level 2 doesn't have a property for centering things vertically. There will probably be one in CSS level 3. But even in CSS2 you can center blocks vertically, by combining a few properties. The trick is to specify that the outer block is to be formatted as a table cell, because the contents of a table cell can be centered vertically.

<div style="border:1px solid #CC6699; width:11em; height:5.5em;text-align:center;vertical-align:middle;display:table-cell;">
    <img style="width:10em; height:5em;" src="path">
</div>

EDIT

As rpflo suggests, using the background-position property is especially great if the container happens to be smaller than the image. Just remember to include the "background-repeat:none" style if you don't want the image to be tiled.

Joshua
Keep in mind that later in your css life display:table-cell won't play nicely with other styles (like floating).
rpflo
I agree with rpflo - not a good solution.Tables are for Tables and not for design.
ChrisBenyamin
A: 

Try this:

<html>
<head>
<style>
#wrap {
width: 500px;
text-align: center;
}
.pic {
padding: 5px;
border: 2px solid #000;
}
</style>
</head>
<body>
<div id="wrap">
 <img src="logo.gif" class="pic">
</div>
</body>
</html>
ChrisBenyamin
A: 

OK, thanks a lot. The table stuff helped :o)