更改file文件上传默认CSS样式

前言: 多数时候我们需要表单上传文件,如图片。但是浏览器默认的input[file]样式很不友好, 需要我们自己手动修改.

如图基于bootstrap布局的表单, 但file文件上传样式不敢恭维.

1 <div class="form-group">
2         <label for="avatar" class="col-md-2 control-label">上传头像:</label>
3         <div class="col-md-6">
4           <input type="file" name="avatar" id="avatar" class="form-control">
5         </div>
6 </div>

1. 首先在input[file]外层套一个容器(如div)

1 <div class="form-group">
2    <label for="avatar" class="col-md-2 control-label">上传头像:</label>
3    <div class="col-md-6">
4        <div class="avatar"><input type="file" name="avatar" id="avatar" class="form-control">点击这里上传文件</div>
5     </div>
6 </div>

2. 定义div.avatar样式, 和input[file]样式

 1 .avatar {
 2     position: relative;
 3     display: block;
 4     overflow: hidden;
 5     width: 100%;
 6     height: 34px;
 7     line-height: 34px;
 8     border: 1px solid #99D3F5;
 9     border-radius: 4px;
10     text-align: center;
11     background: #D0EEFF;
12     cursor: pointer;
13 }
14 .avatar input {
15     display: inline-block;
16     position: absolute;    // 设置input绝对定位,后面的文字才能往上移动
17     font-size: 12px;
18     top: 0;
19     left: 0;
20     opacity: 0;        // 将原来的input变透明
21     z-index: 1;
22     cursor: pointer;
23 }

效果如图: 

原文地址:https://www.cnblogs.com/hughes5135/p/9267488.html