I have a simple HTML button which contains text and an image:
HTML: (Already on http://jsfiddle.net/EFwgN)
<span class="Button">
<img src="http://www.connectedtext.com/Image/ok.gif" />
Small Icon
</span>
CSS:
span.Button {display:inline-block; margin:2px 4px;padding:3px 6px;
background-color:#ddd; height:24px; line-height:24px;
vertical-align:middle;}
span.Button img {vertical-align:middle;}
I can't come up with a combination that would fit these requirements:
line-height
to center the text.Here's a jsfiddle with my current code: http://jsfiddle.net/EFwgN
(note the small icon is slightly below the center of the button)
Answer: Use the CSS vertical-align Property You can align an image vertically center inside a <div> by using the CSS vertical-align property in combination with the display: table-cell; on the containing div element.
Use the position property with the “relative” value for the parent element to place it relative to its normal position. Use the position property with the “absolute” value for the child element to place it relative to its positioned parent element. Add the height, margin-top, top, border, and width properties.
Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.
A simple solution, if you need no less than IE8 (in Standards mode): http://jsfiddle.net/kizu/EFwgN/31/
Just add margin: -100px 0
to img
, so the negative margin would eat any large height:
span.Button img {vertical-align:middle; margin:-100px 0;
position:relative; top:-2px;}
I've added position: relative; top:-2px;
just to look it better :)
But if you'll need support for compatibility mode or IE lt 8 (for some reason), the thing with margin won't work. So you'll need an extra markup: http://jsfiddle.net/kizu/EFwgN/28/, but it's somewhat hacky and works only with the fixed button's height (like in your example).
Use table-based display. Requires shrinking of image due to conflict between display:table-cell;
and height:24px
. Very similar to your aborted attempt from the comments, but includes the required display:block;
on the image: http://jsfiddle.net/shanethehat/5ck3s/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With