---
title: "input type=\"file\" CSS"
author: "orange5458"
date: "2011-11-28T21:27:51Z"
tags: []
categories: ["Web前端"]
slug: "input-type-file-css"
draft: false
lastmod: "2011-11-28T21:29:36Z"
id: 1282021
url: "https://orange5458.iteye.com/blog/1282021"
---

1.原理

基于安全性考虑，IE不支持用程序设置input type=file的值。

所以不能直接用&lt;input type="text"/&gt;和&lt;input type="button"/&gt;代替，

CSS美化file组件的方法是使用position属性将file组件置于&lt;input type="text"/&gt;和&lt;input type="button"/&gt;之上，

然后使其全透明化，操作时使用户感觉在操作&lt;input type="text"/&gt;和&lt;input type="button"/&gt;，实际上还是在操作file组件。 

 

2.源代码

```
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>定义input type="file" 的样式</title>
<style type="text/css">
.type-file-box {    
 position:absolute; 
 width:260px
}

input {    
vertical-align:middle;    
margin:0;    
padding:0
}

.type-file-text {    
height:22px;    
border:1px solid #cdcdcd;    
width:180px;
}

.type-file-button {    
background-color:#FFF;    
border:1px solid #CDCDCD;    
height:24px;    
width:70px;
}

.type-file-file {    
position:absolute;    
top:0;    
right:0;    
height:24px;
filter:alpha(opacity:0);        
width:260px
}
</style>
</head>
<body>
<div class="type-file-box">
<form action="" method="post" name="form1" id="form1">
<input type='text' name='textfield' id='textfield' class='type-file-text' />
<input type='button' name='button' id='button' value='浏览...' class='type-file-button' />
<input name="fileField" type="file" class="type-file-file" id="fileField" size="28" onchange="javascript:document.getElementById('textfield').value=this.value;"/>
</form>
</div>
</body>
</html>
```

 

3.注释

 外层DIV的position属性不能省略。因为

 1)absolute :

生成绝对定位的元素，相对于 static 定位以外的第一个父元素进行定位。

元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定

 2)static :

默认值。没有定位，元素出现在正常的流中（忽略 top, bottom, left, right 或者 z-index 声明）。

 

4.参考资料

[http://www.jb51.net/web/39559.html](http://www.jb51.net/web/39559.html)

 

[http://www.w3school.com.cn/css/pr\_class\_position.asp](http://www.w3school.com.cn/css/pr_class_position.asp)