将图标添加到引导程序下拉菜单项

G-M*_*Man 7 css twitter-bootstrap drop-down-menu

我正在尝试在引导程序下拉菜单中添加一些图标(请参阅下面的小提琴),因为您可以看到图标被添加,但是它会将男性项目向右推,并且该菜单项目不再与其他项目对齐.

这样做的适当方法是什么?

在此输入图像描述

小提琴

<div class="pull-left">
<div class="pull-right">
    <div class="btn-group">                 
            <a class="btn btn-mini dropdown-toggle" data-toggle="dropdown" href="#">
                <span>Actions</span>
                <span class="caret"></span>
            </a>
            <ul class="dropdown-menu">
                <li><a href="#"><i class="icon-ok"></i>Item 1</a></li>
                <li><a href="#">Item 2</a></li>
                <li><a href="#">Item 3</a></li>
                <li class="divider"></li>
                <li><a href="#">Item 4</a></li>
                <li><a href="#">Item 5</a></li>

            </ul>
        </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Bri*_*kau 17

这是我在Bootstrap 3.x中做到这一点的方式:

带图标的菜单

标记:

<ul class="dropdown-menu">
  <li><a href="#" class="icon"><span
         class="glyphicon glyphicon-user"></span>User Profile</a></li>
  <li><a href="#">Log Out</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

CSS:

.dropdown-menu a.icon {
  position: relative;
  padding-left: 40px;
}
.dropdown-menu a.icon .glyphicon {
  top: 6px;
  left: 10px;
  font-size: 18px;
}
Run Code Online (Sandbox Code Playgroud)

关键是glyphicons是绝对定位的,即使它们被"包含"在<a>标记内部,默认情况下定位也相对于整个菜单.通过将.icon类添加到包含图标的每个菜单锚点,它允许您相对于该锚点进行定位,并且还可以填充锚文本以使图标具有正确显示的空间.如上所示,任何不包含.icon类或glyphicon的菜单项都将正常显示为文本链接.

如果原始问题的意图是始终将文本垂直对齐图标,则只需将填充移动到.dropdown-menu a.


Ada*_*her 0

这会起作用。不幸的是,您似乎需要在背景图像上使用!important,这通常是最好避免的。请注意,某些较旧的浏览器不支持 nth-of-type。

@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');

.container {
    margin-top: 10px;
}

/* First Menu Item */
.dropdown-menu li:nth-of-type(1) { 
    background-image: url("http://files.softicons.com/download/application-icons/32x32-free-design-icons-by-aha-soft/png/32/Color%20test.png") !important; 
    background-repeat: no-repeat;
    background-size: 16px 16px;
    background-position: 3px 5px;
    padding-left: 5px;
}

/* Second Menu Item */
.dropdown-menu li:nth-of-type(2) { 
    background-image: url("http://files.softicons.com/download/application-icons/32x32-free-design-icons-by-aha-soft/png/32/Color%20test.png") !important; 
    background-repeat: no-repeat;
    background-size: 16px 16px;
    background-position: 3px 5px;
    padding-left: 5px;
}
Run Code Online (Sandbox Code Playgroud)

JS 小提琴:http://jsfiddle.net/syVk8/

编辑:好的,经过一些澄清后,事实证明您根本不希望文本移动。这是一个类似的示例,左侧没有填充,并且有一个名为“ok”的类,您可以将其应用于不同的菜单项以添加复选框(或任何您的图标):

li.ok { 
    background-image: url("http://files.softicons.com/download/application-icons/32x32-free-design-icons-by-aha-soft/png/32/Color%20test.png") !important; 
    background-repeat: no-repeat;
    background-size: 16px 16px;
    background-position: 3px 5px;
}
Run Code Online (Sandbox Code Playgroud)

JS 小提琴:http://jsfiddle.net/syVk8/2/