如何在jquery按钮上居中图标+文本

时间:2012-12-12 10:13:28

标签: javascript jquery html css button

我为UI创建的按钮由图标和一些文本组成,因此:

  [ <icon> Some Text ]

我正在使用jQuery创建按钮,使用这样的HTML:

<button class="myButton" type="button"/>

和这样的JavaScript:

$('.myButton').button({
                    label: "Some Text",
                    icons: {
                        primary: "icon-custom",
                    }
                })
                .css({ width: '85px' });

设计团队已经规定了它应该如何看的要求,所以我需要一个85px宽的按钮(我管理那个位),图标和文本之间有5个像素的间隙,然后将图标+文本居中在按钮内配对。

这可能,如果可行,怎么样?我无法弄明白。

似乎默认是左对齐按钮上的图标,然后将文本居中左侧,但这看起来不太好。

2 个答案:

答案 0 :(得分:2)

是的,有点难以将图标居中,如果你设置text: false就可以完成,但是你只会得到按钮图标,没有按钮文字。

但你可以做一些css技巧来获得它:

.ui-button-icon-primary 
{
   left:5.5em !important;    // default it is 0.5, so it's always on left position...
}​

根据您的要求修改left值。

jsfiddle

答案 1 :(得分:1)

不是很优雅,但应该照顾你的要求。

$('.myButton').button({
    label: '<span class="ui-button-icon-primary ui-icon icon-custom"></span>text',
}).css({
    width: 85
}).find('.ui-icon').css({
    display:'inline-block',
    position:'relative',
    top:4, //top varies depending on button height / font-size, adapt as needed
    marginRight:5
});

Fiddle

这样,图标就是居中文字范围的一部分。你只需要补偿垂直对齐。