Trouble (vertically) Centering Text in another DIV with relative % sizing - css

Disclaimer: I don't believe this is a duplicate as I'm using relative sizes to produce a full screen grid layout without using px.
Problem: In this jsFiddle http://jsfiddle.net/X3ZDy/73/ I have four equally proportioned boxes. They are designed to span the screen width and remain square. Contained within them are some sample square DIVs (40% x 40%). I'm struggling though to get a text label lbl horizontally and vertically centered within bbl.
All the examples I've seen (and tried) don't work as they require me to know the height of my label, or they use browser restricted table-layout tricks. I need to do this with all relative sizes as per the fiddle.
Can anyone assist? I need to this to work on ALL browsers with a pure CSS (no JS) solution. I'm astonished that it appears to be quite so tricky to vertically align text in a div. I don't mind if we use block or inline elements as the text label.
Please note that I'm NOT looking for a TABLE solution, this is a DIV & CSS puzzle that requires a working jsFiddle.
More:
Thanks all for your answers, but for future posters, note that (width == padding-bottom) is the magic that allows my DIVs to be square. It's key to a grid-layout system so I need to maintain that.
updated
It's pretty tricky working with relative sizes and no fixed heights, but I think I've finally found an answer to the problem (below).

I think I finally found an answer to the problem that works. The issue is that almost every other solution I've seen can't cope when the child size changes and none of the heights are known. I needed this to work for a responsive all % design where there are no fixed heights anywhere.
I stumbled across this SO answer Align vertically using CSS 3 which was my inspiration.
Firstly, using an all % design, you need a zero height wrapper element to act as a positioning placeholder within the parent element;
<body>
<div class="container">
<div class="divWrapper">
<div class="tx">This text will center align no matter how many lines there are</div>
</div>
</div>
</body>
My Container in this case is a simple box tile;
.container
{
margin:2%;
background-color:#888888;
width:30%;
padding-bottom:30%; /* relative size and position on page */
float: left;
position:relative; /* coord system stop */
top: 0px; /* IE? */
}
So nothing special about that except that it has no height which makes this general problem of centering elements tricky. It needs to be absolutely positioned so that we can uses positioning coordinates in the child elements (I think this may require a 'top' in IE).
Next, the wrapper which is absolutely positioned to exactly overlay the parent element and fill it out completely.
.divWrapper
{
position:absolute;
top:0px;
padding-top:50%; /* center the top of child elements vetically */
padding-bottom:50%;
height:0px;
}
The padding means that any child elements will start in exactly the middle of the parent element but this wrapper itself has no height and takes up no space on the page.
Nothing new yet.
Finally, the child element we want to center. The trick here to this was to have the child element slide up vertically based on it's own height. You can't use 50%, because that's 50% of the parent container not ourself. The deceptively simple answer is to use a transform. I can't believe I didn't spot this before;
.tx
{
position: relative;
background-color: transparent;
text-align: center; /* horizontal centering */
-webkit-transform: translateY(-50%); /* child now centers itself relative to the midline based on own contents */
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-ms-filter: 'progid:DXImageTransform.Microsoft.Matrix(M11=0.5, M12=0, M21=0, M22=0.5, SizingMethod="auto expand")'; /*IE8 */
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.5, M12=0, M21=0, M22=0.5, SizingMethod='auto expand'); /*IE6, IE7*/
transform: translateY(-50%);
}
Here's the Fiddle
However, I haven't tested this on IE6+ so if somebody would like to verify my Matrix transform I'd appreciate it.
Update
It turns out that the wrapper isn't even needed. This is all you need to properly vertically center;
.tx
{
width:100%; // +1 to #RonM
position: absolute;
text-align: center;
padding-top:100%;
-webkit-transform: translateY(-50%); /* child now centers itself relative to the midline based on own contents */
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
-ms-filter: 'progid:DXImageTransform.Microsoft.Matrix(Dx=0,Dy=0)'; /*IE8 */
filter: progid:DXImageTransform.Microsoft.Matrix(Dx=0,Dy=0); /*IE6, IE7*/
transform: translateY(-50%);
}
And the updated Fiddle
But still not working in IE6 yet - looking at those transforms, I don't think this can be done for that legacy without JavaScript.

The reality is, that the only tags in HTML that have native fluid vertical alignment are the table cells.
CSS does not have anything that would get you what you want. Not today.
If the requirements are:
1. Works with every browser
2. fluid height
3. vertical centering
4. no scripting
5. No TABLEs
6. You want the solution today, not in few years
You are left with 1 option:
1. Drop ONE of your requirements
Otherwise this "puzzle" is not completable. And this is the only complete acceptable answer to your request.
... if only I could get all the salaries for the wasted hours on this particular challenge :)

Don't self-abuse; let IE7 go... :) (According to this, not very many people are using it.)
I gave this a shot with two approaches, one uses display: table and the other uses line-height. Unfortunately, I don't have access to a PC, so they're only tested in Chrome 25.0.1365.1 canary, FF 18, and Safari 6.0 on Mac 10.8.1, iOS 6.0.1 Safari, and iOS Simulator 5.0 and 5.1 Safari.
The display: table approach has issues on iOS Simulator 5.0 and 5.1, the text isn't quite centered, vertically.
According to quirksmode, the display:table method should be compatitible with IE8 and up. Theorectically, the line-height method might be compatible with IE 6/7.
To create the centered box within each square, I set .box6 to position: relative and changed the .bc style to:
.bc {
position:absolute;
top: 30%;
bottom: 30%;
left: 30%;
right: 30%;
overflow: hidden;
}
Each approach creates a very tall container with a static height inside the .bc element. The exact value for the static height is arbitrary, it just needs to be taller than the content it will contain.
The display: table method changes the .bbl and .bbl .lbl styles to:
.bbl {
display: table;
height: 500px;
padding-top: 50%;
margin-top: -250px;
background-color: blanchedalmond;
width: 100%;
}
.bbl .lbl {
display: table-cell;
vertical-align: middle;
text-align:center;
}
For the line-height method, the HTML is:
<div class="bc">
<div id="line-h-outter">
<span id="line-h-inner">a lot more text than in the other blob. The quick brown fox jumped over the lazy dog</span>
</div>
</div>
CSS:
#line-h-outter {
line-height: 500px;
vertical-align: middle;
margin-top: -250px;
padding-top: 50%;
}
#line-h-inner {
display: inline-block;
line-height: normal;
vertical-align: middle;
text-align: center;
width: 100%;
}
http://jsfiddle.net/X3ZDy/93/

The title should be Centering in the Unknown ;-)
I updated your example using tables: http://jsfiddle.net/uWtqY/ and the text is align inside the box you described using tables, but you don't want this.
Added a table with like:
<table width="100%" height="100%"><tr><td>One line</td></tr> </table></div>
inside <div class="lbl">
Just for cross-browser support.
EDIT
After doing some research indeed it is really hard to v-align an element inside percentages.
Tried a lot of stuff but your code I am not sure if it fits the design of all of them. Well what I mean in other words is that you might first need to construct your vertical alignment and then try to play with percentages. From my experience in this field I learned that a good approach is start designing from the inside elements and then go out if complexity increases. So having percentages in everything might not be the best implementation (and it is not when coming to mobile devices).
EDIT 2
After consolidating with several of my work partners and really geeks on the area of HTML the answer was clear. Either you support < IE7 and you do that with a table or ghost elements or spans, either you use all of the tequniques that are described in several posts and you can have support for >=IE7 . Another option is to use specific structure for each browser.
The link that I think explains it as it is and has a nice title (basically is what you need):
-> Centering in the Unknown
Hope the best.
PS. Links for reference:
http://web.archive.org/web/20091017204329/http://www.zann-marketing.com/developer/20050518/vertically-centering-text-using-css.html
http://css-tricks.com/vertically-center-multi-lined-text/
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
Let me know if it helps

I updated the css to utilize a "spacer" class. It is placed before your "bc" div and inside the colored boxes. This gave me the effect I think you requested.
html:
<div class="rgCol boxCol box6" style="background-color:lightgray">
<div class="spacer"></div>
<div class="bc">
css
.spacer {width:100%;padding-bottom:30%;display:block; }
I bottom padded the spacer by 30% and then moved the absolute left position of your "bbl" div to 30% (from 2%). The blanchdelemond boxes retain their shape and size.
http://jsfiddle.net/X3ZDy/37/

Today I have stumbled upon similar problem - to both vertically and horizontally center child element of a square divs which have precentually set width (they are made sqare using the padding technique). I had to use it for images while maintaining aspect ratio, but changing the child into any target element would be simple.
For this situation no line-height, margin/padding or display:table-cell workaround is suitable. But there is a solution using margin: auto.
HTML:
<div class="squareContainer>
<div class="contentWrapper">
<img class="imagePreview" alt="Image preview" src="//URL.jpg">
</div>
</div>
CSS:
div.squareContainer {
position: relative;
box-sizing: border-box;
height: 0;
padding-bottom: 25%;
width: 25%;
}
div.contentWrapper {
position: absolute;
bottom: 0;
left: 0;
right: 0;
top: 0;
}
img.imagePreview {
display: block;
position: absolute;
bottom: 0;
left: 0;
right: 0;
top: 0;
margin: auto; /* This is the important line */
max-height: 90%;
max-width: 90%;
}
Helpful resources:
http://jsfiddle.net/mBBJM/1/
http://codepen.io/HugoGiraudel/pen/ucKEC
Hope that helps!

You can solve this trivially, without all the weirdness (perhaps someday they'll fix the CSS box model, but till then):
<table>
<tr>
<td width="50" height="50" align="center" valign="middle">text</td>
</tr>
</table>
That's all there is to it. Choose your width and height, drop it in a div and call it good.
The idea of never using tables is a very poor guideline, to the point of being self-abusive.

Do you mean like this?
<div class="mycontainer">
<div class="rgRow">
<div class="rgCol" style="background-color:pink">
<div class="boxCol">BOX1</div>
</div>
<div class="rgCol" style="background-color:lightgray">
<div class="boxCol">
<div class="boxLabel">a lot more text than in the other blob. The quick brown fox jumped over the lazy dog</div>
</div>
</div>
<div class="rgCol" style="background-color:maroon">
<div class="boxCol">
<div class="boxLabel">One liner</div>
</div>
</div>
<div class="rgCol" style="background-color:yellow">
<div class="boxCol">BOX4</div>
</div>
</div>
</div>
.mycontainer
{
background-color: #000000;
display: inline-table;
}
.rgRow
{
width: 100%;
display: table-row;
}
.rgCol
{
width: 25%;
height: 100%;
text-align: center;
vertical-align: middle;
display: table-cell;
}
.boxCol
{
display: inline-block;
width: 100%;
text-align: center;
vertical-align: middle;
}
.boxLabel
{
text-align: center;
vertical-align: middle;
background-color: blanchedalmond;
overflow: hidden;
margin: 2%;
width: 96%;
height: 96%;
}

Related

How to stop mobile safari from setting fixed positions to absolute on input focus?

Disclaimer - I understand there exists questions around fixed elements in safari, and fixed elements weren't supported, but now are and so forth. However I can't find a question that addresses this exact question.
Given the simplest of fixed sidebars, something like:
.sidebar {
position: fixed;
top: 10px;
right: 10px;
}
And a relatively long page, with input elements.
When an input element is focused, any fixed element becomes absolute - I understand the why, safari is trying to declutter the viewport - thats fine, but not always appropriate. I ask that I get to choose the best experience for the user (i know best naturally).
So the Question..
Is there any way to leave fixed elements as fixed even when input elements are focused?
I have attempted to do a bit of $(window).on('scroll', magic and position elements manually on scroll, but its quite jittery on the ipad.
Safari has supported position: fixed since at least version 9.2, but if you're seeing difficult issues, you can fully create the fixed position effect by making the document element and body full screen and then using absolute positioning. Scrolling then occurs in some main container element rather than the body. Your "fixed" elements can exist anywhere in the markup using this method.
jsfiddle here
html,
body,
.mainContainer {
height: 100%;
width: 100%;
overflow: hidden;
margin: 0;
}
.mainContainer {
overflow: auto;
}
.fixed {
position: absolute;
bottom: 20px;
left: 20px;
}
In order to achieve the effect you desire you need to change your approach to the layout. Instead of positioning the sidebar with position:fixed you need to use position:absolute within a position:relative container that is set to the height of the viewport within that position:relative container you need another div that uses overflow-y: scroll and -webkit-overflow-scrolling : touch
Caveat: I generally avoid using position fixed on tablet & mobile if possible although the browser support is there, in my experience it'll be janky and javascript solutions leave a lot to be desired, my first response would be to challenge the pattern with the designer. If I'm given designs that include a position fixed element when there are input elements, I'm more likely to seek a design solution than a development one as the focus issues you're describing are difficult to circumvent and maintain a quality user experience.
THE MARKUP:
<div class="outer">
<div class="sidebar">
<ul>
<li>Dummy list nav or something</li>
</ul>
</div>
<div class="container">
<input type="text" />
<!-- I added 10000 inputs here as a demo -->
</div>
</div>
THE CSS:
html,body{
-webkit-overflow-scrolling : touch !important;
overflow: auto !important;
height: 100% !important;
}
.outer {
position: relative;
overflow: hidden;
/* I'm using Viewport Units here for ease, but I would more likely check the height of the viewport with javascript as it has better support*/
height: 100vh;
}
.sidebar {
position: absolute;
top: 10px;
right: 10px;
/*added bg colour for demo */
background: blue;
}
.container {
height: 100vh;
overflow-y: scroll;
-webkit-overflow-scrolling: touch
}
input {
display: block;
}
Here's a CodePen for you to open in your simulator (presentation view):
https://codepen.io/NeilWkz/full/WxqqXj/
Here's the editor view for the code:
https://codepen.io/NeilWkz/pen/WxqqXj

*Perfect* vertical image alignment

I have a square div of fixed size and wish to place an arbitrary size image inside so that it is centred both horizontally and vertically, using CSS. Horizontally is easy:
.container { text-align: center }
For the vertical, the common solution is:
.container {
height: 50px;
line-height: 50px;
}
img {
vertical-align: middle;
}
But this is not perfect, depending on the font size, the image will be around 2-4px too far down.
To my understanding, this is because the "middle" used for vertical-align is not really the middle, but a particular position on the font that is close to the middle. A (slightly hacky) workaround would be:
container {
font-size: 0;
}
and this works in Chrome and IE7, but not IE8. We are hoping to make all font lines the same point, in the middle, but it seems to be hit-and-miss depending on the browser and, probably, the font used.
The only solution I can think of is to hack the line-height, making it slightly shorter, to make the image appear in the right location, but it seems extremely fragile. Is there a better solution?
See a demo of all three solutions here:
http://jsfiddle.net/usvrj/3/
Those without IE8 may find this screenshot useful:
If css3 is an option, then flexbox does a good job at vertical and horizontal aligning:
UPDATED FIDDLE
.container {
display:flex;
align-items: center; /* align vertical */
justify-content: center; /* align horizontal */
}
How about using your image as a background? This way you could center it consistently everywhere. Something along these lines:
margin:5px;
padding:0;
background:url(http://dummyimage.com/50) no-repeat center center red;
height:60px;
width:60px;
This is REALLY hacky, but it is what we used to do in the ie6 days.
.container {
position: relative;
}
img {
position: absolute;
top: 50%;
left: 50%;
margin-top: -12px; // half of whatever the image's height is, assuming 24px
margin-left: -12px; // half of whatever the image's width is, assuming 24px
}
I may be missing something in this example, but you get the idea.
Have you tried the following:
img {
display: block;
line-height: 0;
}
I usually use this hack, but I haven't really checked it that thoroughly in IE8.
Here is a small JS Fiddle I have made: http://jsfiddle.net/rachit5/Ge4YH/
I believe it matches your requirement.
HTML:
<div>
<img src=""/>
</div>
CSS:
div{height:400px;width:400px;position:relative;border:1px solid #000;}
img{position:absolute;top:0;left:0;right:0;bottom:0;margin:auto;}

How do I centre absolutely positioned content of unknown width?

Before someone asks me why the hell I would want to do this let me come straight out and tell you. That way one of you clever peeps out there can tell me a far better way...
I'm making a viewer for paintings which should stretch to fill the page, well 90% of the height of the screen to be precise. I want to fade the paintings in one over the other and want to center each of them in the middle of the screen.
To fade the paintings in over each other I need to position them 'absolute' to stop them from stacking. Here's where the trouble comes. Ever since I've set them to absolute, every method I use to center the containing div hasn't worked.
Part of the problem is that I'm not setting any width for the paintings as I want them to dynamically size themselves to fill 90% of the user's screen.
I've found a hundreds of methods for centering absolute content and believe I might need to shrink wrap the containing div. However I've not had any success as of yet.
HTML-
<div id="viewer_div">
<img src="" id="first" />
<img id="second" class="hidden"/>
</div>
Style Sheet
#viewer_div {
width:1264px;
}
img {
height:90%;
display:block;
margin-left: auto;
margin-right:auto;
}
The above gives me the desired effect, but doesn't allow me to position the images absolute. Can anyone suggest a way of centering the images but also allows me to fade one over the other?
Pushing the element left by 50% of its width and then translating it horizontally by 50% has worked for me.
.element {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
I found the concept in the following link, and then I translated to fit my horizontal align needs: https://gist.github.com/colintoh/62c78414443e758c9991#file-douchebag-vertical-align-css
Either use JavaScript to calculate the width and move it,
use a CSS hack to move the element right and left by 50%,
or don't absolutely position it.
This answer is incredibly short, but it is to the point. If you require something to be centralised (meaning you would like the browser to determine where the centre point is, and position it there), then you can't use absolute positioning - because that takes away control from the browser.
To fade the paintings in over each other I need to position them
'absolute' to stop them from stacking.
This is where your problem lies. You have assumed that you need absolute positioning for the wrong reason.
If you are experiencing problems placing elements on top of each other, wrap the images in an absolutely positioned container which is 100% width and has text-align: center
If you do feel that absolute positioning is necessary, the following hack can be used to achieve your desired results:
div {
position: absolute;
/* move the element half way across the screen */
left: 50%;
/* allow the width to be calculated dynamically */
width: auto;
/* then move the element back again using a transform */
transform: translateX(-50%);
}
Obviously the above hack has a terrible code smell, but it works on some browsers. Be aware: this hack is not necessarily obvious to other developers, or other browsers (especially IE or mobile).
To go off of Samec's answer, you can also use this to center an absolute position element vertically and horizontally of unknown dimensions:
#viewer_div {
position: relative;
}
#viewer_div img {
position: absolute;
left: 50%;
top: 0%;
transform: translate(-50%, 50%);
}
Centering div with position: absolute and width: unknown:
HTML:
<div class="center">
<span></span>
<div>
content...
</div>
</div>
CSS:
.center{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: grid;
grid-template-columns: auto auto;
/* if you need the overflow */
overflow: auto;
}
You can use this solution even if the content is wider than the screen width, and don't need to transform: translate (which can blur elements)
How it works:
Grid will insert a span before the first auto, and insert a div right before the second auto, and you get:
span(0px) - auto - div(...px) - auto
auto will be equal to each other.
Same for vertical centering, but write grid-template-rows instead of a grid-template-columns
2021
A modern approach to absolutely centered content with grid and inset
The inset CSS property is a shorthand that corresponds to the top, right, bottom, and/or left. MDN
#viewer_div {
display: grid;
place-items: center;
position: absolute;
inset: auto 0;
}
*,
::after,
::before {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
body {
width: 100vw;
height: 100vh;
background-color: hsl(201, 27%, 10%);
position: relative;
}
#viewer_div {
display: grid;
place-items: center;
position: absolute;
inset: auto 0;
background-color: hsl(197, 7%, 21%);
color: white;
}
<div id="viewer_div">
<h1>Title 2021</h1>
<img src="https://via.placeholder.com/180x100.png/09f/fff" id="first" />
</div>

Dynamic size, two column layout with one column vertically and horizontally aligned, legacy browser support

I am trying to create a two column layout, with content in column 1 both horizontally and vertically aligned in the middle, whereby the content of column 2 will vary in size. The width of both columns is fixed to 50% of the width of the screen.
In modern CSS complaint browsers I can simply do the following:
CSS:
#wrapper
{
display: table;
width: 100%;
/* for illustration purposes */
background: #ddd;
}
#left-column
{
display: table-cell;
width: 50%;
text-align: center;
vertical-align: middle;
/* for illustration purposes */
background: #fdd;
}
#right-column
{
display: table-cell;
/* for illustration purposes */
background: #ddf;
}
HTML:
<div id="wrapper">
<div id="left-column">
<p>I am both horizontally and vertically centered in column 1</p>
</div>
<div id="right-column">
<p>I am dynamic content in column 2, i.e. my size will vary</p>
<p>I am dynamic content in column 2, i.e. my size will vary</p>
<p>I am dynamic content in column 2, i.e. my size will vary</p>
<p>I am dynamic content in column 2, i.e. my size will vary</p>
<p>I am dynamic content in column 2, i.e. my size will vary</p>
</div>
</div>
However, the bad news is I also need this to work in IE6, and IE7...
The solutions I've seen so far are quite ugly and involve lots of nested divs. What's the cleanest way to achieve this so that it will work in all browsers? I've experimented with float: left, for the two column layout, but my main problem is the vertical alignment in the first column.
PS. I don't want to use tables for the layout, although it does work, it's bad for screen readers and therefore breaks my accessibility guidelines.
Thanks in advance!
With static content on the left-hand column, your solution is simple: use fixed heights and padding.
CSS
#left-column {
height: 50%; /* adjust height dependent on N&S padding */
padding: 20% 0; /* adds north and south padding to "center" #left-content */
}
#left-content {
height: 10%; /* adjust to exactly fit content */
text-align: center;
/* basically for testing, this will help us find the ideal
* percentage for our #left-content height. */
overflow: hidden;
background-color: red;
}
HTML
<div id="left-column">
<div id="left-content">
your image and text goes here
</div><!-- /left-content -->
</div><!-- /left-column -->
In your CSS, you will need to adjust the heights and paddings to achieve your desired result.
I would suggest ensuring the content in #left-content is 100% responsive. This may not be a 100% solution, but with some work on it (#media queries, etc), you should be able to achieve your goal in every browser and viewport size. The only thing I can think of off the top of my head that might break something like this is user-increased font size.
Unfortunately vertically centering something is either going to take javascript or a few ugly nested divs. If you are a maniacal purist I would recommend a float left, top aligned left column and enhance with javascript to be pushed to center.
That said, a couple wrapper divs never killed anyone.
Cracked it, I think... Html as in the original post, and CSS as follows:
#wrapper
{
width: 100%;
overflow: hidden;
position: relative;
/* for illustration purposes */
background: #ddd;
}
#wrapper p { font-size:1em; margin: .5em; }
#right-column
{
margin-left: 50%;
overflow: hidden;
/* for illustration purposes */
background: #ddf;
}
#left-column
{
width: 50%;
height: 2em;
position: absolute;
left: 0;
top: 50%;
margin-top: -1em;
text-align: center;
/* for illustration purposes */
background: #fdd;
}
The margin on the inner <p> tag needs setting so that we know what the height will be (the different browsers seem to default the margin of a <p> differently if you don't explicitly set it), I used em so that it scales nicely on different displays.
It's funny how something this simple can be such a pain to achieve... I'm still not 100% happy with it as if the content of column 1 wraps on a small display (or minimised window), then it won't be vertically aligned properly...

align icons with text

What's the best way to align icons (left) and text (right) or the opposite text on left and icon on right?
Does the icon image and text have to be the same size? Ideally I would like them to be different but be on the same vertical alignment.
I am using background-position css property to get the icons from a larger image.
Here is how I do it now, but I am struggling with either getting them to be on the same line or be vertically aligned to the bottom.
Text
This is what I get after I try your suggestions.
Though the text is now aligned with the icon, it is superimposed over the icon to the right of the icon that I want. Please note that i am using the background position to show the icon from a larger set of images.
Basically I am getting
<icon><10px><text_and_unwanted_icon_to_the_right_under_it>
<span class="group3_drops_icon group3_l_icon" style="">50</span>
group3_drops_icon {
background-position:-50px -111px;
}
.group3_l_icon {
-moz-background-clip:border;
-moz-background-inline-policy:continuous;
-moz-background-origin:padding;
background:transparent url(/images/group3.png) no-repeat scroll left center;
height:35px;
overflow:hidden;
padding-left:55px;
}
I usually use background:
<style type="text/css">
.icon {
background-image: url(path/to/my/icon.jpg);
background-position: left center;
background-repeat: no-repeat;
padding-left: 16px; /* Or size of icon + spacing */
}
</style>
<span class="icon">Some text here</span>
You can do it on the same line using vertical-align and line-height
<p style='line-height: 30px'>
<img src='icon.gif' style='vertical-align: middle' />Icon Text
</p>
Alternatively, you can go the background approach with no-repeat and positioning:
span.icontext {
background: transparent url(icon.gif) no-repeat inherit left center;
padding-left: 10px /* at least the width of the icon */
}
<span class="icontext">
Icon Text
</span>
Sadly, neither of these answers are bullet proof and each have one big flaw.
#rossipedia
I used to implement all my icons this way and it works quite well. But, and this is a big but, it does not work with sprites, since you're using the background-position property to position the icon inside the container that includes your text.
And not using sprites where you can is bad for performance and SEO, making them imperative for any good modern website.
#Jamie Wong
The first solution has two markup flaws. Using elements semantically correctly is sadly underrated by some, but you'll see the benefits in prioritizing form in your search engine ranking. So first of all, you shouldn't use a p-tag when the content is not a paragraph. Use span instead. Secondly, the img-tag is meant for content only. In very specific cases, you might have to ignore this rule, but this isn't one of them.
My Solution:
I won't lie to you, I've checked in a lot of places in my time and IMHO there is no optimal solution. These two solutions are the ones that come closest to that, though:
Inline-Block Solution
HTML:
<div class="container">
<div class="icon"></div>
<span class="content">Hello</span>
</div>
CSS:
.container {
margin-top: 50px;
}
.container .icon {
height: 30px;
width: 30px;
background: #000;
display: inline-block;
vertical-align: middle;
}
.container .content {
display: inline-block;
vertical-align: middle;
}
"display:inline-block;" is a beautiful thing. You can do so much with it and it plays very nicely with responsive design.
But it depends on your client. Inline-Block does not work well with IE6, IE7 and still causes problems with IE8. I personally no longer support IE6 and 7, but IE8 is still out there. If your client really needs his website to be usable in IE8, inline-block is sadly no option. Assess this first. Replace the black background of the icon-element with your sprite, position it, throw no-repeat in there and voilĂ , there you have it.
Oh yeah, and as a plus, you can align the text any way you want with vertical-align.
P.S.: I am aware that there's an empty HTML-tag in there, if anyone has a suggestion as to how to fill it, I'd be thankful.
Fixed Height Solution
.clearfix:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.clearfix {
display: inline-block;
}
html[xmlns] .clearfix {
display: block;
}
* html .clearfix {
height: 1%;
}
.container {
margin-top: 50px;
border: 1px solid #000;
}
.container .icon {
height: 30px;
width: 30px;
background: #000;
float:left;
}
.container .content {
line-height: 30px;
float: left;
display: block;
}
I hate this one. It uses a fixed line height for the text, and if you choose the same height as the Icon's box, the text is centered to that height. To align the text to the top, cut the line height, and as to the bottom, you'll have to fix that with position: absolute and a fixed width and height for the container. I'm not going to get into that unless someone requests it, because it's a whole issue for itself, and brings with it a lot of disadvantages.
The main disadvantage of this path is the fixed height. Fixed heights are always unflexible and especially with text, it can cause a bunch of problems (You can no longer scale the text as a user without it being cut off, plus different browsers render text differently). So be sure that in no browser the text is cut off and that it has some wiggle room inside its line height.
P.S.: Don't forget the clearfix for the container. And, of course, replace the black background with your sprite and according position + no-repeat.
Conclusion
Use inline-block if at all possible. ;) If it's not, breath deeply and try the second solution.

Resources