[英]How can I have centered text and right-aligned image in the same element?
我有一些th
在他們的文本元素應該居中,它們也包含圖片:
向上/向下箭頭圖形是單獨的圖像。
我的問題是,在保持文本居中的同時將圖像定位在th
元素右側的最簡單可靠的方法是什么?
如果有相當簡單的方法,我願意使用jQuery / JavaScript。
一個警告:我需要上下圖形作為單獨的圖像,而不是頁眉背景的一部分。
<th>
Title
<img src='/images/sort_unsorted.jpg' />
</th>
究竟你是怎么想的文本為中心,由左/右邊緣等距th
或從左側邊緣th
到圖像的左側? 兩者之間的差異很小,因為您的圖像相對較小,但仍然可以識別。
與圖像等距,解決方案很容易(如Marcus回答):
th img { float:right; }
等距th
邊緣需要多一點的,因為你需要打破圖像出來的頁面流:
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;
*/
}
編輯:固定在表單元格中的位置(感謝布蘭登),這是一個簡單的小提琴: http : //jsfiddle.net/brillyfresh/4LDZ9/
為了更好地定位(如果您不想使用背景圖像),您必須將內容包裝在塊級元素中,例如DIV。 您不能使用position: absolute;
在表格單元格的子元素上。
所以,我推薦這樣的東西:
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>
想象<div class="img"> </div>
只是一個12px x 12px的圖像。
的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;
}
這里要記住的重要一點是,您要給positioning
div的左側和右側提供足夠的填充,以為圖像騰出空間(即: padding: 10px 32px;
)。 否則,圖像將與您的文本重疊。
這是一個小提琴: http : //jsfiddle.net/brandondurham/nXQeR/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.