Стилизация кнопки input type="file"

Как вы стилизуете кнопку ввода type="file"?

Ответ 1

Обработка файловых вводов общеизвестно сложна, так как большинство браузеров не изменят внешний вид ни CSS, ни Javascript.

Даже размер ввода не будет реагировать на подобные:

<input type="file" style="width:200px">

Вместо этого вам нужно будет использовать атрибут размера:

<input type="file" size="60" />

Для любого более сложного стиля (например, изменение внешнего вида кнопки обзора) вам нужно будет рассмотреть хитрый подход к наложению стилизованной кнопки и поля ввода поверх ввода исходного файла. Статья, уже упомянутая rm на www.quirksmode.org/dom/inputfile.html, является лучшей, которую я видел.

Ответ 2

Для этого вам не нужен JavaScript! Вот кросс-браузерное решение:

См. этот пример! - Он работает в Chrome/FF/IE - (IE10/9/8/7)

Лучшим подходом было бы иметь собственный элемент ярлыка с атрибутом for, прикрепленным к элементу ввода скрытый. (Атрибут label for должен соответствовать элементу файла id, чтобы это работало).

<label for="file-upload" class="custom-file-upload">
    Custom Upload
</label>
<input id="file-upload" type="file"/>

В качестве альтернативы вы также можете просто обернуть элемент ввода файла меткой напрямую: (пример)

<label class="custom-file-upload">
    <input type="file"/>
    Custom Upload
</label>

С точки зрения стиля просто скройте элемент 1 используя селектор атрибутов .

input[type="file"] {
    display: none;
}

Затем все, что вам нужно сделать, это стиль пользовательского элемента label. (пример).

.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}

1 - Стоит отметить, что если вы спрячете элемент с помощью display: none, он не будет работать в IE8 и ниже. Также помните о том, что jQuery validate по умолчанию не проверяет скрытые поля. Если одна из этих проблем является для вас проблемой, вот два разных метода, чтобы скрыть ввод ( 1, 2), которые работают в этих обстоятельствах.

Ответ 3

следуйте этим шагам, чтобы создать собственные стили для формы загрузки файлов:

  1. это простая форма HTML (пожалуйста, прочитайте комментарии HTML, которые я написал здесь ниже)

    <form action="#type your action here" method="POST" enctype="multipart/form-data">
      <div id="yourBtn" style="height: 50px; width: 100px;border: 1px dashed #BBB; cursor:pointer;" onclick="getFile()">Click to upload!</div>
      <!-- this is your file input tag, so i hide it!-->
      <div style='height: 0px;width:0px; overflow:hidden;'><input id="upfile" type="file" value="upload"/></div>
      <!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
      <input type="submit" value='submit' >
    </form>
    
  2. затем используйте этот простой скрипт для передачи события click в тег ввода файла.

    function getFile(){
         document.getElementById("upfile").click();
    }
    

    Теперь вы можете использовать любой тип стилей, не беспокоясь о том, как изменить стили по умолчанию.

Я знаю это очень хорошо, потому что я пытался изменить стили по умолчанию в течение полутора месяцев. поверьте мне, это очень сложно, потому что разные браузеры имеют разные теги ввода загрузки. Так что используйте этот для создания ваших пользовательских форм загрузки файлов. Вот полный код АВТОМАТИЧЕСКОГО ЗАГРУЗКИ.

function getFile() {
  document.getElementById("upfile").click();
}

function sub(obj) {
  var file = obj.value;
  var fileName = file.split("\\");
  document.getElementById("yourBtn").innerHTML = fileName[fileName.length - 1];
  document.myForm.submit();
  event.preventDefault();
}
#yourBtn {
  position: relative;
  top: 150px;
  font-family: calibri;
  width: 150px;
  padding: 10px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border: 1px dashed #BBB;
  text-align: center;
  background-color: #DDD;
  cursor: pointer;
}
<form action="#type your action here" method="POST" enctype="multipart/form-data" name="myForm">
  <div id="yourBtn" onclick="getFile()">click to upload a file</div>
  <!-- this is your file input tag, so i hide it!-->
  <!-- i used the onchange event to fire the form submission-->
  <div style='height: 0px;width: 0px; overflow:hidden;'><input id="upfile" type="file" value="upload" onchange="sub(this)" /></div>
  <!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
  <!-- <input type="submit" value='submit' > -->
</form>

Ответ 4

Скройте его с помощью css и используйте пользовательскую кнопку с помощью кнопки $(selector).click(), чтобы активировать кнопку обзора. затем установите интервал, чтобы проверить значение типа ввода файла. интервал может отображать значение для пользователя, чтобы пользователь мог видеть, что загружается. интервал будет очищаться, когда форма будет отправлена ​​[ИЗМЕНИТЬ] Извините, что я был очень занят, это значит обновить этот пост, вот пример

<form action="uploadScript.php" method="post" enctype="multipart/form-data">
<div>
    <!-- filename to display to the user -->
    <p id="file-name" class="margin-10 bold-10"></p>

    <!-- Hide this from the users view with css display:none; -->
    <input class="display-none" id="file-type" type="file" size="4" name="file"/>

    <!-- Style this button with type image or css whatever you wish -->
    <input id="browse-click" type="button" class="button" value="Browse for files"/>

    <!-- submit button -->
    <input type="submit" class="button" value="Change"/>
</div>

$(window).load(function () {
    var intervalFunc = function () {
        $('#file-name').html($('#file-type').val());
    };
    $('#browse-click').on('click', function () { // use .live() for older versions of jQuery
        $('#file-type').click();
        setInterval(intervalFunc, 1);
        return false;
    });
});

Ответ 5

HTML

<div class="new_Btn">SelectPicture</div><br>
<input id="html_btn" type='file'" /><br>

CSS

.new_Btn {
// your css propterties
}

#html_btn {
 display:none;
}

JQuery

$('.new_Btn').bind("click" , function () {
        $('#html_btn').click();
    });
//edit: 6/20/2014: Be sure to use ".on" not ".bind" for newer versions of jQuery

Fiddle: http://jsfiddle.net/M7BXC/

Вы также можете достичь своих целей без jQuery с обычным JavaScript.

Теперь newBtn является ссылкой на html_btn, и вы можете создать свой новый бит, как вы хотите: D

Ответ 6

Все механизмы рендеринга автоматически генерируют кнопку при создании <input type="file">. Исторически эта кнопка была полностью несовместимой. Однако Trident и WebKit добавили крючки через псевдоэлементы.

Trident

Как и в IE10, кнопка ввода файла может быть написана с использованием псевдоэлемента ::-ms-browse. В принципе, любые правила CSS, которые вы применяете к обычной кнопке, могут быть применены к псевдоэлементу. Например:

::-ms-browse {
  background: black;
  color: red;
  padding: 1em;
}
<input type="file">

Ответ 7

Если вы используете Bootstrap 3, это сработало для меня:

См. http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/

.btn-file {
  position: relative;
  overflow: hidden;
}
.btn-file input[type=file] {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 100%;
  min-height: 100%;
  font-size: 100px;
  text-align: right;
  filter: alpha(opacity=0);
  opacity: 0;
  outline: none;
  background: white;
  cursor: inherit;
  display: block;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<span class="btn btn-primary btn-file">
    Browse...<input type="file">
</span>

Ответ 8

Я могу сделать это с помощью чистого CSS, используя приведенный ниже код. Я использовал bootstrap и font-awesome.

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />

<label class="btn btn-default btn-sm center-block btn-file">
  <i class="fa fa-upload fa-2x" aria-hidden="true"></i>
  <input type="file" style="display: none;">
</label>

Ответ 9

 <label>
    <input type="file" />
 </label>

Вы можете обернуть ваш input type="file" внутри метки для ввода. Стиль этикетки, но вы хотите и скрывать ввод с дисплеем: none;

Ответ 10

Рабочий пример здесь с собственной поддержкой Drag and drop: https://jsfiddle.net/j40xvkb3/

Стилизируя ввод файла, вы не должны нарушать любые нативные взаимодействия, которые обеспечивает ввод.

display: none подход не нарушает встроенную поддержку перетаскивания.

Чтобы ничего не нарушать, вы должны использовать подход opacity: 0 для ввода и расположить его, используя относительный/абсолютный шаблон в оболочке.

Используя эту технику, вы можете легко dragenter зону щелчка/отбрасывания для пользователя и добавить пользовательский класс в javascript dragenter события dragenter чтобы обновить стили и дать пользователю обратную связь, чтобы он мог видеть, что он может удалить файл.

HTML:

<label for="test">
  <div>Click or drop something here</div>
  <input type="file" id="test">
</label>

CSS:

input[type="file"] {
  position: absolute;
  left: 0;
  opacity: 0;
  top: 0;
  bottom: 0;
  width: 100%;
}

div {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ccc;
  border: 3px dotted #bebebe;
  border-radius: 10px;
}

label {
  display: inline-block;
  position: relative;
  height: 100px;
  width: 400px;
}

Вот рабочий пример (с дополнительным JS для обработки события dragover и dragover файлов).

https://jsfiddle.net/j40xvkb3/

Надеюсь, это помогло!

Ответ 11

Это просто с jquery. Чтобы привести пример кода Ryan с небольшими изменениями.

Базовый html:

<div id="image_icon"></div>
<div id="filename"></div>
<input id="the_real_file_input" name="foobar" type="file">

Обязательно настройте стиль на входе, когда будете готовы: opacity: 0 Вы не можете установить display: none, потому что его нужно кликать. Но вы можете позиционировать его под "новой" кнопкой или подтащить что-то еще с z-index, если хотите.

Настройте некоторые jquery, чтобы щелкнуть реальный ввод, когда вы щелкните изображение.

$('#image_icon').click(function() {
    $('#the_real_file_input').click();
});

Теперь ваша кнопка работает. Просто измените и вставьте значение при изменении.

$('input[type=file]').bind('change', function() {
    var str = "";
    str = $(this).val();
    $("#filename").text(str);
}).change();

Тах, да! Вам может понадобиться проанализировать значение val() для чего-то более значимого, но вы должны быть настроены.

Ответ 12

Вот решение, которое на самом деле не стилирует элемент <input type="file" />, но вместо этого использует элемент <input type="file" /> поверх других элементов (которые можно стилизовать). Элемент <input type="file" /> на самом деле не заметен, поэтому общая иллюзия имеет красиво оформленный контроль загрузки файлов.

Недавно я столкнулся с этой проблемой, и, несмотря на множество ответов на Stack Overflow, никто, похоже, не соответствовал законопроекту. В конце концов, я закончил настройку, чтобы иметь простое и элегантное решение.

Я также тестировал это на Firefox, IE (11, 10 и 9), Chrome и Opera, iPad и нескольких устройствах Android.

Здесь ссылка JSFiddle → http://jsfiddle.net/umhva747/

$('input[type=file]').change(function(e) {
    $in = $(this);
    $in.next().html($in.val());
    
});

$('.uploadButton').click(function() {
    var fileName = $("#fileUpload").val();
    if (fileName) {
        alert(fileName + " can be uploaded.");
    }
    else {
        alert("Please select a file to upload");
    }
});
body {
    background-color:Black;
}

div.upload {
    background-color:#fff;
    border: 1px solid #ddd;
    border-radius:5px;
    display:inline-block;
    height: 30px;
    padding:3px 40px 3px 3px;
    position:relative;
    width: auto;
}

div.upload:hover {
    opacity:0.95;
}

div.upload input[type="file"] {
    display: input-block;
    width: 100%;
    height: 30px;
    opacity: 0;
    cursor:pointer;
    position:absolute;
    left:0;
}
.uploadButton {
    background-color: #425F9C;
    border: none;
    border-radius: 3px;
    color: #FFF;
    cursor:pointer;
    display: inline-block;
    height: 30px;
    margin-right:15px;
    width: auto;
    padding:0 20px;
    box-sizing: content-box;
}

.fileName {
    font-family: Arial;
    font-size:14px;
}

.upload + .uploadButton {
    height:38px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data">
    <div class="upload">
        <input type="button" class="uploadButton" value="Browse" />
        <input type="file" name="upload" accept="image/*" id="fileUpload" />
        <span class="fileName">Select file..</span>
    </div>
    <input type="button" class="uploadButton" value="Upload File" />
</form>

Ответ 13

ВИДИМОСТЬ: скрытый TRICK

Обычно я использую трюк visibility:hidden

это моя стилизованная кнопка

<div id="uploadbutton" class="btn btn-success btn-block">Upload</div>

это кнопка типа ввода = файл. Обратите внимание на правило visibility:hidden

<input type="file" id="upload" style="visibility:hidden;">

это бит JavaScript для их склеивания. Он работает

<script>
 $('#uploadbutton').click(function(){
    $('input[type=file]').click();
 });
 </script>

Ответ 14

Единственный способ, о котором я могу думать, это найти кнопку с javascript после ее рендеринга и присвоить ей стиль

вы также можете посмотреть эту запись

Ответ 15

<input type="file" name="media" style="display-none" onchange="document.media.submit()">

Я бы обычно использовал простой javascript для настройки тега ввода файла. Скрытое поле ввода, нажатие кнопки, javascript вызывает скрытое поле, простое решение без каких-либо css или кучу jquery.

<button id="file" onclick="$('#file').click()">Upload File</button>

Ответ 16

Поместите кнопку загрузки файла поверх красивой кнопки или элемента и скройте ее.

Очень просто и будет работать в любом браузере

<div class="upload-wrap">
    <button type="button" class="nice-button">upload_file</button>
    <input type="file" name="file" class="upload-btn">
</div>

Стили

.upload-wrap {
    position: relative;
}

.upload-btn {
    position: absolute;
    left: 0;
    opacity: 0;
}

Ответ 17

Здесь мы используем интервал для ввода ввода файла типа и , который мы просто настроили для этого диапазона, поэтому мы можем добавить любой стиль с помощью этого способа.

Примечание, что мы используем тег ввода с видимостью: скрытая опция и запускаем ее в промежутке.

.attachFileSpan{
color:#2b6dad;
cursor:pointer;
}
.attachFileSpan:hover{
text-decoration: underline;
}
<h3> Customized input of type file </h3>
<input id="myInput" type="file" style="visibility:hidden"/>

        <span title="attach file" class="attachFileSpan" onclick="document.getElementById('myInput').click()">
        Attach file
        </span>

Ответ 18

ТОЛЬКО CSS

Используйте этот очень простой и EASY

Html:

<label>Attach your screenshort</label>
                <input type="file" multiple class="choose">

Css:

.choose::-webkit-file-upload-button {
    color: white;
    display: inline-block;
    background: #1CB6E0;
    border: none;
    padding: 7px 15px;
    font-weight: 700;
    border-radius: 3px;
    white-space: nowrap;
    cursor: pointer;
    font-size: 10pt;
}

Ответ 19

Может быть, много абрисов. Но мне это нравится в чистом CSS с fa-кнопками:

.divs {
    position: relative;
    display: inline-block;
    background-color: #fcc;
}

.inputs {
    position:absolute;
    left: 0px;
    height: 100%;
    width: 100%;
    opacity: 0;
    background: #00f;
    z-index:999;
}

.icons {
    position:relative;
}
<div class="divs">
<input type='file' id='image' class="inputs">
<i class="fa fa-image fa-2x icons"></i>
</div>

<div class="divs">
<input type='file' id='book' class="inputs">
<i class="fa fa-book fa-5x icons"></i>
</div>
<br><br><br>
<div class="divs">
<input type='file' id='data' class="inputs">
<i class="fa fa-id-card fa-3x icons"></i>
</div>





<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Ответ 20

Это хороший способ сделать это с загрузкой файла material/angular. Вы можете сделать то же самое с кнопкой начальной загрузки.

Примечание. Я использовал <a> вместо <button>, это позволяет пузырьковым событиям пузыриться.

<label>
    <input type="file" (change)="setFile($event)" style="display:none" />

    <a mat-raised-button color="primary">
      <mat-icon>file_upload</mat-icon>
      Upload Document
    </a>

  </label>

Ответ 21

Вот решение, которое также отображает выбранное имя файла: http://jsfiddle.net/raft9pg0/1/

HTML:

<label for="file-upload" class="custom-file-upload">Chose file</label>
<input id="file-upload" type="file"/>
File: <span id="file-upload-value">-</span>

JS:

$(function() {
    $("input:file[id=file-upload]").change(function() {
        $("#file-upload-value").html( $(this).val() );
    });
});

CSS

input[type="file"] {
    display: none;
}

.custom-file-upload {
      background: #ddd;
      border: 1px solid #aaa;
      border-top: 1px solid #ccc;
      border-left: 1px solid #ccc;
      -moz-border-radius: 3px;
      -webkit-border-radius: 3px;
      border-radius: 3px;
      color: #444;
      display: inline-block;
      font-size: 11px;
      font-weight: bold;
      text-decoration: none;
      text-shadow: 0 1px rgba(255, 255, 255, .75);
      cursor: pointer;
      margin-bottom: 20px;
      line-height: normal;
      padding: 8px 10px; }

Ответ 22

На этой неделе мне также нужно было настроить кнопку и отобразить выбранное имя файла в стороне от нее, поэтому, прочитав некоторые из приведенных выше ответов (спасибо BTW), я придумал следующую реализацию:

HTML:

<div class="browse">
<label id="uploadBtn" class="custom-file-upload">Choose file
<input type="file" name="fileInput" id="fileInput" accept=".yaml" ngf-select ngf-change="onFileSelect($files)" />
</label>
<span>{{fileName}}</span>
</div>

CSS

   input[type='file'] {
    color: #a1bbd5;
    display: none;

}

.custom-file-upload {
    border: 1px solid #a1bbd5;
    display: inline-block;
    padding: 2px 8px;
    cursor: pointer;
}

label{
    color: #a1bbd5;
    border-radius: 3px;
}

Javascript (Angular)

app.controller('MainCtrl', function($scope) {

        $scope.fileName = 'No file chosen';

          $scope.onFileSelect = function ($files) {
          $scope.selectedFile = $files;
          $scope.fileName = $files[0].name;
    };
});

В основном я работаю с ng-file-upload lib, Angular -wise Я связываю имя файла с моей областью $и даю ему начальное значение "No file selected", я также привязываю onFileSelect() в мою область, поэтому, когда выбран файл, я получаю имя файла с помощью ng-upload API и назначаю его в $scope.filename.

Ответ 23

Не обманывайте себя "отличными" решениями только для CSS, которые на самом деле очень специфичны для браузера или накладывают стилизованную кнопку поверх реальной кнопки или заставляют вас использовать <label> вместо <button> или любой другой такой хак. JavaScript необходим, чтобы заставить его работать для общего использования. Пожалуйста, изучите, как gmail и DropZone делают это, если вы мне не верите.

Просто создайте обычную кнопку, но вы хотите, а затем вызовите простую функцию JS, чтобы создать и связать скрытый элемент ввода с вашей стилизованной кнопкой.

<!DOCTYPE html>
<meta charset="utf-8">

<style>
    button {
        width            : 160px;
        height           : 30px;
        font-size        : 13px;
        border           : none;
        text-align       : center;
        background-color : #444;
        color            : #6f0;
    }
    button:active {
        background-color : #779;
    }
</style>

<button id="upload">Styled upload button!</button>

<script>

function Upload_On_Click(id, handler) {
    var hidden_input = null;
    document.getElementById(id).onclick = function() {hidden_input.click();}
    function setup_hidden_input() {
        hidden_input && hidden_input.parentNode.removeChild(hidden_input);
        hidden_input = document.createElement("input");
        hidden_input.setAttribute("type", "file");
        hidden_input.style.visibility = "hidden";
        document.querySelector("body").appendChild(hidden_input);
        hidden_input.onchange = function() {
            handler(hidden_input.files[0]);
            setup_hidden_input();
        };
    }
    setup_hidden_input();
}

Upload_On_Click("upload", function(file) {
    console.log("GOT FILE: " + file.name);
});

</script>

Обратите внимание, как приведенный выше код повторно связывает его после каждого выбора пользователем файла. Это важно, потому что "onchange" вызывается только в том случае, если пользователь меняет имя файла. Но вы, вероятно, захотите получить файл каждый раз, когда пользователь предоставит его.

Ответ 24

css может многое сделать здесь... с небольшим обманом...

<div id='wrapper'>
  <input type='file' id='browse'>
</div>

#wrapper {
     width: 93px; /*play with this value */
     height: 28px; /*play with this value */
     background: url('browseBtn.png') 0 0 no-repeat;
     border:none;
     overflow:hidden;
}

#browse{
     margin-left:-145px; /*play with this value */
     opacity:0; /* set to .5 or something so you can better position it as an overlay then back to zero again after you're done */
     -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
     filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
}

:: reference:: http://site-o-matic.net/?viewpost=19

-abbey

Ответ 25

Я нашел очень простой способ переключить кнопку файла на картинку. Вы просто помечаете изображение и помещаете его поверх кнопки с файлом.

<html>
<div id="File button">
    <div style="position:absolute;">
        <!--This is your labeled image-->
        <label for="fileButton"><img src="ImageURL"></label>
    </div>
    <div>
        <input type="file" id="fileButton"/>
    </div>
</div>
</html>

При нажатии на помеченное изображение вы выбираете кнопку файла.

Ответ 26

Здесь простое решение css, которое создает согласованную целевую область и позволяет вам стилизовать ваши faux-элементы, как вам нравится.

Основная идея такова:

  • У вас есть два "поддельных" элемента (текстовый ввод/ссылка) в качестве сиблингов для вашего реального входа в файл. Абсолютно позиционируйте их так, чтобы они точно соответствовали вашей целевой области.
  • Оберните свой файл с помощью div. Установите переполнение в скрытое (так что входной файл не выйдет) и сделайте его точно таким, каким вы хотите, чтобы ваша целевая область была.
  • Установите непрозрачность 0 на вход файла, чтобы он был скрыт, но все еще доступен для клика. Дайте ему большой размер шрифта, чтобы вы могли щелкнуть все части целевой области.

Здесь jsfiddle: http://jsfiddle.net/gwwar/nFLKU/

<form>
    <input id="faux" type="text" placeholder="Upload a file from your computer" />
    <a href="#" id="browse">Browse </a>
    <div id="wrapper">
        <input id="input" size="100" type="file" />
    </div>
</form>

Ответ 27

Действительно умное решение с использованием jQuery, которое работает во всех старых браузерах, а также в новых, я нашел здесь. Он заботится обо всех проблемах с стилем и щелчком(), используя фактическую кнопку просмотра файлов. Я сделал простую версию javascript: fiddle Решение так же просто, как и гений: сделайте входной файл невидимым и используйте кусок кода, чтобы поместить его под мышь.

<div class="inp_field_12" onmousemove="file_ho(event,this,1)"><span>browse</span>
<input id="file_1" name="file_1" type="file" value="" onchange="file_ch(1)">
</div>
<div id="result_1" class="result"></div>


function file_ho(e, o, a) {
    e = window.event || e;
    var x = 0,
    y = 0;
    if (o.offsetParent) {
        do {
        x += o.offsetLeft;
        y += o.offsetTop;
        } while (o = o.offsetParent);
    }
var x1 = e.clientX || window.event.clientX;
var y1 = e.clientY || window.event.clientY;
var le = 100 - (x1 - x);
var to = 10 - (y1 - y);
document.getElementById('file_' + a).style.marginRight = le + 'px';
document.getElementById('file_' + a).style.marginTop = -to + 'px';
}

.inp_field_12 {
position:relative;
overflow:hidden;
float: left;
width: 130px;
height: 30px;
background: orange;
}
.inp_field_12 span {
position: absolute;
width: 130px;
font-family:'Calibri', 'Trebuchet MS', sans-serif;
font-size:17px;
line-height:27px;
text-align:center;
color:#555;
}
.inp_field_12 input[type='file'] {
cursor:pointer;
cursor:hand;
position: absolute;
top: 0px;
right: 0px;
-moz-opacity:0;
filter:alpha(opacity: 0);
opacity: 0;
outline: none;
outline-style:none;
outline-width:0;
ie-dummy: expression(this.hideFocus=true);
}
.inp_field_12:hover {
background-position:-140px -35px;
}
.inp_field_12:hover span {
color:#fff;
}

Ответ 28

Если вы ищете библиотеку javascript - из готового решения, jquery-fileinput отлично работает.

Ответ 29

Обновить Nevermind, это не работает в IE или это новый брат, FF. Работает над любым другим типом элемента, как ожидалось, но не работает с файлами. Гораздо лучший способ сделать это - просто создать ввод файла и ярлык, который ссылается на него. Сделайте отображение ввода файла ничем и стрелой, он работает в IE9 + без проблем.

Предупреждение: все ниже этого дерьмо!

Используя псевдоэлементы, расположенные/размерные для их контейнера, мы можем получить только один входной файл (без дополнительной разметки) и стиль, как обычно.

Демо

<input type="file" class="foo">

.foo {
    display: block;
    position: relative;
    width: 300px;
    margin: auto;
    cursor: pointer;
    border: 0;
    height: 60px;
    border-radius: 5px;
    outline: 0;
}
.foo:hover:after {
    background: #5978f8;
}
.foo:after {
    transition: 200ms all ease;
    border-bottom: 3px solid rgba(0,0,0,.2);
    background: #3c5ff4;
    text-shadow: 0 2px 0 rgba(0,0,0,.2);
    color: #fff;
    font-size: 20px;
    text-align: center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: block;
    content: 'Upload Something';
    line-height: 60px;
    border-radius: 5px;
}

Наслаждайтесь парнями!

Старое обновление

Превратили это в микшер Stylus. Должно быть достаточно легко для одного из вас, прохладно кошек SCSS, чтобы преобразовать его.

file-button(button_width = 150px)
  display block
  position relative
  margin auto
  cursor pointer
  border 0
  height 0
  width 0
  outline none
  &:after
    position absolute
    top 0
    text-align center
    display block
    width button_width
    left -(button_width / 2)

Использование:

<input type="file">

input[type="file"]
    file-button(200px)

Ответ 30

В качестве JGuo и CorySimmons вы можете использовать интерактивное поведение стилизованного ярлык, скрывающий менее гибкий элемент ввода файла.

<!DOCTYPE html>
<html>
<head>
<title>Custom file input</title>
<link rel="stylesheet" href="#" onclick="location.href='http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css'; return false;">
</head>

<body>

<label for="upload-file" class="btn btn-info"> Choose file... </label>
<input id="upload-file" type="file" style="display: none"
onchange="this.nextElementSibling.textContent = this.previousElementSibling.title = this.files[0].name">
<div></div>

</body>
</html>