【CSS】表单样式(2)

809 阅读3分钟

这是我参与11月更文挑战的第28天,活动详情查看:2021最后一次更文挑战


表单样式(2)

接着介绍剩下的几种表单元素

02. 选框样式

结合 <label> 标签,为绑定的选框设置样式

  • 前提条件:<label>标签的for属性要与选框的id属性相同,即进行了绑定

  • 实现思路:

    • 隐藏选框,再为<label>标签添加**::before伪类或者::after伪类**
    • 通过这个伪类设置新的样式
    • 结合选框的**:checked伪类**属性,设置选中状态时的样式
  • 实现过程:(以单选框为例)

    • 隐藏单选框

      input[type="radio"] {
          /* 直接设置大小为0 */
          width: 0;
          height: 0;
      }
      
    • 添加伪类

      label::before {
          content: "";
          display: inline-block;
          /* 用vertical-align来对齐文本 */
          vertical-align: middle;
          width: 20px;
          height: 20px;
          margin-right: 10px;
          border-radius: 50%;
          border: 5px solid darkgreen;
      }
      
:checked
  • 通过:checked属性来控制选中状态

    input[type="radio"]:checked + label::before {
        background-color: lightgreen;
        padding: 0px;
    }
    
  • 或者直接给<label>标签设置样式,再结合**:checked伪类**属性,设置选中样式

03. 按钮样式

  • 先设置基本样式,用常用的属性就可以设置

    input[type=button],
    input[type=submit],
    input[type=reset] {
        width: 80px;
        height: 30px;
        color: white;
        background-color: #5bb85d;
        font-size: 18px;
        font-weight: bold;
    }
    
  • 主要是边框样式,和文本框样式的边框设置一样,使用border属性,更改默认的边框样式,使用outline属性,更改默认轮廓样式

    input[type=button],
    input[type=submit],
    input[type=reset] {
        /* border+outline */
        border-radius: 3px;
        border: none;
        outline: none;
    }
    

其它的还可以通过伪类属性,设置点击时的样式**:active**,聚焦时的样式**:focus**,等等

04. 下拉框样式

  • 基本样式还是可以用已知的属性来设置,对于边框仍然采用border+outline属性来设置

    select {
        width: 150px;
        height: 30px;
        color: #444;
        font-size: 16px;
        font-weight: bold;
        /* border+outline */
        border-radius: 3px;
        border: 3px solid skyblue;
        outline: none;
    }
    
text-align-lastappearance
  • 通过text-align-last属性,来控制下拉框里的文字居中

  • 通过appearance属性,隐藏下拉箭头

    select {
        /* 文字间距 */
        letter-spacing: 2px;
        /* 文字居中 */
        text-align-last: center;
        appearance: none;
        /* 背景颜色 */
        background-color: #fff;
        background: linear-gradient(white, #e5e5e5);
    }
    
  • 对于option元素,只能设置一般的字体文本样式

    option {
        font-size: 14px;
        font-weight: bold;
        color: red;
        background-color: #adff2f;
    }
    

    只有字体文本样式才会生效

    • 无法设置位置样式、悬浮样式

    • 背景颜色无法透明,透明时默认白色


    因此,要更改option的样式,只能通过其它元素模拟来实现下拉框

  • 其它的,在行内设置样式size属性multiple属性

    <select size=2>...</select>
    

    表示显示两个选项出来

    这时下拉框里的内容被option里的内容填充,显示数量为两个选项,且此时通过滚动来切换显示

    select{
        /* 取消高度 */
        /* height:30px */
        /* 文本垂直方向居中对齐 */
       vertical-align: middle;
    }
    
    <select multiple>...</select>
    

    可以搭配size属性,设置具体的显示数量