繁体   English   中英

如何在同一元素中居中放置文本和右对齐图像?

[英]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 img {
    float: right;
}

演示: http : //jsfiddle.net/marcuswhybrow/ZxUMY/

究竟你是怎么想的文本为中心,由左/右边缘等距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">&nbsp;</div>
            </div>
        </th>
        <th>
            <div class="positioning">
                Center
                <div class="img">&nbsp;</div>
            </div>
        </th>
        <th>
            <div class="positioning">
                Right
                <div class="img">&nbsp;</div>
            </div>
        </th>
    </thead>
    <tbody>
        <td>Left</td>
        <td>Center</td>
        <td>Right</td>
    </tbody>
</table>

想象<div class="img">&nbsp;</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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM