如何通过CSS自定义选择元素以实现这种暗色风格?

10

如何创建一个像下面图片展示的选择元素?

enter image description here

我的代码是:

<select>
    <option>-- Select City --</optoin>
    <option>Delhi</option>
    <option>Gurgaon</option>
</select>

这个功能可以用jQuery实现,但我想使用纯CSS。


我真的不确定你在问什么。你想让一张图片出现在每个选择选项的后面吗? - Miles
@Miles,是的,我想在选择选项中使用背景图像,如果可能的话只用纯CSS实现...? - Rohit Azad Malik
由于宽度问题,不建议使用dropkick:https://dev59.com/questions/uGbWa4cB1Zd3GeqPas9m - user1318135
5个回答

24

这是一个使用 CSS 实现的下拉菜单,您可以根据需要自定义它:

label.custom-select {
    position: relative;
    display: inline-block;

}

.custom-select select {
    display: inline-block;
    padding: 4px 3px 3px 5px;
    margin: 0;
    font: inherit;
    outline:none; /* remove focus ring from Webkit */
    line-height: 1.2;
    background: #000;
    color:white;
    border:0;
}

/* Select arrow styling */
.custom-select:after {
    content: "▼";
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    font-size: 60%;
    line-height: 30px;
    padding: 0 7px;
    background: #000;
    color: white;
    pointer-events: none;
}

.no-pointer-events .custom-select:after {
    content: none;
}
<label class="custom-select">
    <select>
        <option>Sushi</option>
        <option>Blue cheese with crackers</option>
        <option>Steak</option>
        <option>Other</option>
    </select>
</label>

JSFiddle


4
使用pointer-events:none;可以让您通过箭头进行点击并激活选择字段,因此该元素的CSS应如下所示。
.custom-select:after {
    content: "▼";
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    font-size: 60%;
    line-height: 30px;
    padding: 0 7px;
    background: #000;
    color: white;
    pointer-events:none;
}

0

如果没有使用Javascript,就无法自定义选择框,就像您在截图中看到的那样。

您可以在此示例中看到,您可以自定义颜色、填充和边框,但不能自定义按钮本身。


0
option{
  background-image:url(image.png);
  background-repeat: no-repeat;
}

-1

尽管您已将背景图像添加到选择框中,但无法隐藏右侧的处理程序。我建议使用这个: http://jamielottering.github.com/DropKick/

您只需要稍微修改CSS以适应您的需求。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接