I have some th
elements with text in them that should be centered and they also contain images:
The up/down arrow graphic is a separate image.
My question is, what is the simplest reliable way to position that image over to the right side of the th
element while keeping the text centered?
I'm open to using jQuery/JavaScript if there's a reasonably simple way to do it.
One caveat: I need the up/down graphic to be a separate imag开发者_开发知识库e, not part of the header background.
<th>
Title
<img src='/images/sort_unsorted.jpg' />
</th>
Just float the image to the right:
th img {
float: right;
}
DEMO: http://jsfiddle.net/marcuswhybrow/ZxUMY/
To get a good handle on positioning (if you don't want to use a background image) you'll have to wrap the content in a block level element, like a DIV. You can't use position: absolute;
on child elements of a table cell.
So, I recommend something like this:
HTML:
<table cellpadding="0" cellspacing="0">
<thead>
<th>
<div class="positioning">
Left
<div class="img"> </div>
</div>
</th>
<th>
<div class="positioning">
Center
<div class="img"> </div>
</div>
</th>
<th>
<div class="positioning">
Right
<div class="img"> </div>
</div>
</th>
</thead>
<tbody>
<td>Left</td>
<td>Center</td>
<td>Right</td>
</tbody>
</table>
Imagine <div class="img"> </div>
is just a 12px x 12px image.
CSS
table {
border: 10px solid rgb(230,230,230);
color: white;
}
table thead th,
table tbody td {
background: black;
border: solid 1px white;
font: bold 12px Helvetica, Arial, sans-serif;
padding: 10px;
}
table thead th {
padding: 0;
text-align: center;
}
table thead .positioning {
padding: 10px 32px;
position: relative;
}
table thead .img {
background: red;
height: 12px;
margin-top: -6px;
position: absolute;
right: 10px;
top: 50%;
width: 12px;
}
The important thing to remember here is that you give the left and right sides of the positioning
div enough padding to make room for the image (ie: padding: 10px 32px;
). Otherwise the image will overlap your text.
Here's a fiddle: http://jsfiddle.net/brandondurham/nXQeR/
Exactly how did you want the text to be centered, equidistant from the left/right edges of the th
or from the left edge of the th
to the left side of the image? There is a small difference between the two since your image is relatively small, but still a discernible difference.
Equidistant to image, the solution is easy (as Marcus answered):
th img { float:right; }
Equidistant to th
edges requires a bit more, since you need to break the image out of the page flow:
th {
display:block;
position:relative;
text-align:center;
}
th img {
position:absolute;
right:0;
/* optional, for vertically centering the image
top:50%;
margin-top:-[image height/2]px;
*/
}
EDIT: fixed for positioning in a table cell (thanks Brandon), and here's a simple fiddle: http://jsfiddle.net/brillyfresh/4LDZ9/
精彩评论