【问题标题】:Separate CSS for label checkbox to label input将标签复选框的 CSS 分离到标签输入
【发布时间】:2013-07-31 15:41:08
【问题描述】:

我在两个输入文本框中都使用了标签:

<label for="Username">Username</label>
<input id="Username"  type="text" value="">

和复选框/单选框

<label for="Live">System is Live</label>
<input id="Live" name="Live" type="checkbox" value="false">

我遇到的麻烦是如何为不同输入类型的标签指定不同的 css。

如果我做一个通用标签 css:

label {
    color: #00a8c3;
    line-height: 20px;
    padding: 2px;
    display: block;
    float: left;
    width: 160px;
}

我发现我要么得到未对齐的复选框,要么得到错误定位的文本框。

【问题讨论】:

    标签: html css


    【解决方案1】:

    您可以向标签添加类。例如:

    <label for="Username" class="textbox-label">Username</label>
    <input id="Username" type="text" value="">
    
    <label for="Live" class="checkbox-label">System is Live</label>
    <input id="Live" name="Live" type="checkbox" value="false">
    

    然后使用 CSS 中的类值:

    label.textbox-label {
     /*some styles here*/
    }
    
    label.checkbox-label {
     /*some styles here*/
    }
    

    或者,如果你在输入之后有标签,你可以这样选择:

    input[type="text"] + label { 
      /*some styles here*/
    }
    
    input[type="checkbox"] + label { 
      /*some styles here*/
    }
    

    【讨论】:

    • 标签也可以有一个ID。因此,如果您想要一个标签的特定样式。
    【解决方案2】:

    你可以这样写 css 选择器:

    label[for=Username]{ /* ...definitions here... / } 
    
    label[for=Live] { / ...definitions here... */ }
    

    【讨论】:

      【解决方案3】:

      你可以这样写你的css选择器:

      label[for=Username] 
      label[for=Live]
      

      你也可以看看这个帖子:
      CSS Selector for selecting an element that comes BEFORE another element?

      【讨论】:

        猜你喜欢
        • 2021-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-30
        • 2018-01-25
        相关资源
        最近更新 更多