样式下拉列表我是MVC

时间:2014-03-27 12:06:43

标签: c# css dropdownlistfor

如何在我的下拉列表中设置每个selectlistitem的样式? 我可以给每个项目一个id并访问css吗? 我试图改变每个项目的背景颜色......

以下是代码:

@Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
                  new List<Object>{ 
                       new { value = 0 , text = "Red" },
                       new { value = 1 , text = "Blue" },
                       new { value = 2 , text = "Green"},

                    },
                  "value",
                  "text",
                   2))

2 个答案:

答案 0 :(得分:1)

Html.DropDownListFor呈现a,所以我不知道为什么你说你没有使用标签。

CSS并不关心服务器端代码,只关注呈现的HTML,因此如果您遇到问题,请始终向我们展示呈现的HTML和您的CSS。

无论如何,要设计元素的样式(并记住因为CSS中的“替换元素”,样式的机会有限,但你可以做一些很酷的事情:http://bavotasan.com/2011/style-select-box-using-only-css/

你可以覆盖id =“”属性,这样就可以在CSS中使用元素选择器,如下所示:

 @Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
                      new List<Object>{ 
                           new { value = 0 , text = "Red" },
                           new { value = 1 , text = "Blue" },
                           new { value = 2 , text = "Green"},

                        },
                      "value",
                      "text",
                       2), new { id = "mySelect" })


        #mySelect { width: 135px; }
//or
 @Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
                      new List<Object>{ 
                           new { value = 0 , text = "Red" },
                           new { value = 1 , text = "Blue" },
                           new { value = 2 , text = "Green"},

                        },
                      "value",
                      "text",
                       2), new { class = "dropdown" })

但是,如果您在局部视图中使用此DropDownListFor,那么id =“”属性在文档中将不是唯一的,这是非法的。尝试使用不同的选择器来使用上下文,例如后代选择器。

答案 1 :(得分:0)

您应该能够使用css伪选择器,例如:

option:nth-child(1) {
    background: red;
}