使用CSS将IMG和文本对齐

时间:2013-03-13 14:09:58

标签: html css

我正在尝试使用跨度制作一个带有图像的按钮。 以下工作,但问题是文本是垂直中间对齐,但保存按钮img是不。我需要在中间对齐所有内容。我的代码出了什么问题?

.ButtonSPAN{
display:inline-block;
color: white;
background-color:#00537B;
border: 1px solid #1E90FF;
height: 25px;

padding:3px;
vertical-align:middle;
font-weight: bold;
}
.ButtonSPAN:hover{
color: #F0E68C;
cursor: hand; cursor: pointer;  
}

<span class="ButtonSPAN"><img src="/common/images/save.png" onclick="Save()">&nbsp;Save</span>

5 个答案:

答案 0 :(得分:2)

结帐this fiddle,说明vertical-align可用的不同值。您的示例CSS显示您将inline-block应用于父级(.ButtonSPAN),这无助于对齐内容。

实现目标的最简单方法是将文本包装在单独的span中,然后使用它:

<button><img src="http://placehold.it/36x36"> <span>Middle</span></button>

button {
    color: white;
    background-color:#00537B;
    border: 1px solid #1E90FF;
    padding: 3px;
    font-weight: bold;
}

img, span {
    display: inline-block;
    vertical-align: middle;
}

以上是jsFiddle的截图。我已经将图片略大一些,并给出了span一个background-color来更好地说明变体:

vertical-align examples

答案 1 :(得分:0)

[已更新] 将您的“保存”包裹在span中,然后添加到您的CSS中

.ButtonSPAN{
    line-height:25px;
}

.ButtonSPAN *{
    vertical-align:middle; //Align everything nested in .ButtonSPAN to the middle
}

演示here

答案 2 :(得分:0)

有些人认为可行。 我的第一个选择是将图像作为background:url(image_path)放置到跨度,并给出高度,宽度和边距以使其正确对齐。您可以放置​​多个背景,只需在您想要点击的位置添加锚点,或者使所有跨度可点击。 第二个选项是将该图像与vertical-align:middle进行对齐。 第三是编辑该图像以在图像上方留出透明空间。

希望这会有所帮助!

答案 3 :(得分:0)

这里有几个选项:

您可以将图像作为背景图像应用于您的范围:

.ButtonSPAN{
    background:#00537B url(/common/images/save.png) 3px center no-repeat;
}

您必须将onClick="save()"放入span元素。

Background-image property

或者,如果你知道图像的高度,这应该有效:

(我假设图像高度为16px)

.ButtonSPAN{
    position:relative;
}
.ButtonSPAN img{
    position:absolute;
    top:50%;
    margin-top:-8px;
}

或者,或者看看这个page

P.S。最好用小写字母开始你的类名。

答案 4 :(得分:0)

当您将文本和图像保存在单个span元素中时,您需要解决如下所示的问题:

<强> Working Fiddle

在这里,我添加了marign-bottom:-3px,使其看起来像文本中间。

.ButtonSPAN img{  
   margin-bottom:-3px;  /* fix until the img comes to mid */
   width:16px;height:16px; /* giving fixed widths for demo */
}

我还从vertical-align课程中删除了.ButtonSPAN,并将line-height添加为等于身高的值。