View Full Version : Centering varying size images in fixed size DIVs
ETpro
12-12-2011, 10:11 PM
I'm up against the centering deficiencies of current CSS. Building a Category page to display a series of products on a dynamically generated eCommerce site. I know that the upper limits of the thumbnail height and width are 140px, so every thumb will be 140 pixels in one dimension. But each product naturally has its own aspect ratio. So a picture of an upright vacuum will likely be 140 pixels high while a Rhomba would be 140 pixels wide but just a few pixels high.
Must I go through writing software to measure image height and write a local style setting the top and bottom margin; or is there some CSS trick that would make Margin: auto; actually work to center vertically and horizontally?
auntnini
12-13-2011, 12:37 AM
See for instance http://www.w3.org/Style/Examples/007/center.en.html
Horizontal centering can be achieved by margin-right: auto and margin-left: auto (margin: 0 auto;.) in most browsers.. Images are inline elements that can be centered with text-align: center. Can set one dimension (width or height) and the other dimension to auto (I think second dimension will adjust to keep aspect ratio without specifying "auto.") Vertical centering is not as easy:
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.
For CSS3 see for instance http://net.tutsplus.com/tutorials/html-css-techniques/html-5-and-css-3-the-techniques-youll-soon-be-using/
#content {
display: table;
}
#mainContent {
display: table-cell;
width: 620px;
padding-right: 22px;
}
aside {
display: table-cell;
width: 300px;
}
Several approaches presented at http://blog.themeforest.net/tutorials/vertical-centering-with-css/ .
For CSS3 Flexible Box see
http://www.456bereastreet.com/archive/201103/the_css3_flexible_box_layout_flexbox/
http://www.css3.info/introducing-the-flexible-box-layout-module/
http://www.wiibart.com/vertical-centering-with-css3
and CSS3 box-align property
http://www.w3schools.com/cssref/css3_pr_box-align.asp
and vertical align http://www.css3.com/css-vertical-align/
You could also cheat with a real <TABLE><TR><TD>align</TD><TR></TABLE>.
ETpro
12-14-2011, 04:00 AM
Thanks, auntnini. I hadn't thought of making the contianing block display: table;. Great idea. If I remember, most real browsers respect that, but lots of versions of pretend browsers like IE don't. But still, it's better than descending back into table hell just to center a bunch of images in a row.
Happy holidays to you.
Jim
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.