Стилизация текстовых полей формы
В этой статье рассмотрим различные варианты стилизации текстовых полей HTML-форм. Сначала создадим базовый вариант оформления input, а затем множество других, дополняя каждый из них небольшим количеством CSS.
Введение
Веб-формы являются неотъемлемой частью многих веб-сайтов. Они позволяют пользователю ввести те или иные данные, которые затем отправляются на сервер или обрабатываются на стороне клиента, например, для изменения интерфейса.
Веб-формы также часто называют HTML-формами . Их проектирование осуществляется с помощью элементов управления форм (текстовых полей, выпадающих списков, кнопок, чекбоксов и т.д.) и некоторых дополнительных элементов, которые используются для придание форме определённой структуры.
Стилизация формы выполняется через CSS. В этом руководстве остановимся и подробно рассмотрим различные варианты оформления её текстовых полей .
Исходные коды примеров расположены на GitHub в папке text-field проекта «ui-components».
Нормализация стилей
1. Настройка box-sizing .
Обычно хорошей практикой считается для всех элементов включая псевдоэлементы установить box-sizing: border-box :
В этом случае браузер при рассчитывании ширины и высоты элементов будет включать в них поля (padding) и границы (border). Как правило, это сильно упрощает работу с размерами элементов, и избавляет нас от множества проблем при размещении контента.
2. Нормализация стилей <input> .
Для того чтобы <input> в разных браузерах отображался как можно более одинаково необходимо добавить следующее:
Базовый вариант оформления input
Для удобного добавления к элементам стилей создадим следующую HTML-разметку:
Т.е. добавим к <input> с type=»text» класс text-field__input , к <label> – text-field__label , а затем обернём их в элемент <div> с классом text-field .
Теперь напишем стили для этих элементов. А также сразу включим в них стили для нормализации, чтобы не добавлять их отдельно:
Примененные CSS свойства к элементу <input> , и то, что они делают:
- display: block – устанавливает блочное отображение;
- width: 100% – занимает всю доступную ширину;
- height: calc(2.25rem + 2px) – высота элемента определяется путём сложения 2.25rem ( font-size * line-height + padding-top + padding-bottom ) и 2px (ширина верхней и нижней границы);
- margin: 0 – убирает margin отступы;
- padding: 0.375rem 0.75rem – внутренние поля: сверху и снизу – 0.375rem, а слева и справа – 0.75rem;
- font-family: inherit – чтобы шрифт был такой как у родительского элемента, а не тот который браузер по умолчанию назначает для <input> ;
- font-size: 1rem – устанавливает явный размер шрифта, иначе будет браться из стилей браузера для <input> ;
- font-weight: 400 – задаёт начертание шрифта;
- line-height: 1.5 – высота строки (1.5 * размер шрифта);
- color: #212529 – цвет шрифта;
- background-color: #fff – цвет фона;
- background-clip: padding-box – указывает, что фон (фоновое изображение) нужно рисовать только до внешнего края отступа (под границей не выводить);
- border: 1px solid #bdbdbd – устанавливает границу, у которой: 1px (толщина), solid (тип линии) и #bdbdbd (цвет);
- border-radius: 0.25rem – радиус скругления углов;
- transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out – выполняет изменение значений свойств border-color и box-shadow с анимацией длительностью 0.15 секунд посредством временной функцией ease-in-out .
В результате получили следующее оформление:

Стилизуем плейсхолдер . По умолчанию плейсхолдер отображается полупрозрачным или светло-серым цветом. Получить его можно с помощью ::placeholder . Оформим его следующим образом:

Стили для <input> в состоянии фокуса (получить это состояние можно с помощью псевдокласса :focus ):

Оформление <input> , когда он находится в состоянии disabled и readonly :

Этот набор стилей будет у нас отправной точкой для создания других.
input с иконкой
Рассмотрим пример вставки в input иконки с помощью псевдоэлементов.
Для этого дополнительно обернём элемент <input> в <div> с классами text-field__icon text-field__icon_email :
Первый класс ( text-field__icon ) будем использовать для того, чтобы установить относительное позиционирование ( position: relative ). Это действие позволит нам разместить иконку в нужном месте относительно input , используя уже абсолютное позиционирование ( position: absolute ). Второй класс ( text-field__icon_email ) будет определять иконку, которую мы хотим вставить.
Ещё один вариант оформления:
input с активной svg-иконкой
В этом примере поместим в input иконку, на которую можно нажать.
Для этого мы также как и в предыдущем примере обернули <input> в <div >. <div> . Саму svg-иконку обернули в <span> с классом text-field__aicon и поместили рядом с <input> .
Оформление выполнили так:
Ещё пример вставки иконки в input :
input с кнопкой
HTML-разметка input с кнопкой:
Расположение кнопки справа от input выполним с помощью флексов:
input с плавающим label
Разметка input с плавающим label:

Ещё один вариант с «плавающей» меткой:


input со счётчиком символов
Пример в котором под input отображается количество набранных символов и максимальная длина:

Это выполняется посредством следующего кода:
Стили для отображения состояния валидации input
Применить стили в зависимости от состояния поля в CSS можно с помощью специальных псевдоклассов. Например, :valid позволяет выбрать валидные элементы, а :invalid — не валидные.
Но, если вы хотите контролировать этот процесс и добавлять стили с помощью JavaScript, то тогда лучше это делать через классы. Например, использовать класс text-field__input_valid при успешной валидации, а text-field__input_invalid — при не успешной. Их следует добавлять к <input> .
Отображать сообщения пользователю или подсказки можно через <div >. </div> .

Для <input> с плавающим <label> :



Пример валидации формы с помощью JavaScript
Валидацию элементов формы будем осуществлять с помощью функции checkValidity() . После этого, в зависимости от её результата, будем добавлять той или иной класс к <input> , а также сообщение ( input.validationMessage ) в элемент .text-field__message .
Т.к. мы будем сами отображать сообщения, то необходимо отключить стандартные подсказки браузера. Для этого к тегу <form> необходимо добавить атрибут novalidate :
Create a search icon inside input box with HTML and CSS
Displaying a search icon inside an input box is a nice way to indicate to the user that it is indeed a search input.
Google search input
Duckduckgo search input
Twitter search input
CodePen search input
Gmail search input
Vimeo search input
Markup
The HTML for our search box with an icon will consist of a form , input , and button elements.
The form will act as a wrapper, as well as will react to the submit event.
The input element should have a type attribute equal to the search value. It will ensure a better usability on mobile devices. The keyboard with a layout suited for search will be shown.
NOTE: To improve UX you can also specify an input placeholder e.g. “Search…”. This will give a user an additional hint that this is indeed a search input.
Finally, the button type attribute should have a submit value. The proper button type will ensure the form can be submitted via button click without additional events for this button. The button will also act as an icon.
Styling
First, we’ll need to set the form element display property value to flex . This will allow us to properly align input and button elements.
We’ll also set a border property to wrap elements closer together.
Next, we need to set styles for our search input box. It should span the full width of the container element, as well as have some visually appealing properties.
Finally, let’s add some styling to the submit button. We will hide the text of the button with text-indent and overflow properties, and display in its place a magnifying glass icon.
To display the icon we can use encoded svg as a background image.
The last touch is to set the :focus state on input and button elements:
No button example
If you’re willing to show an icon inside an input without it being a button, just remove the submit button from the form.
You can leave existing form and input styles but in this case, set the icon as a background for the input.
Как поместить иконку в input
Completing the CAPTCHA proves you are a human and gives you temporary access to the web property.
What can I do to prevent this in the future?
If you are on a personal connection, like at home, you can run an anti-virus scan on your device to make sure it is not infected with malware.
If you are at an office or shared network, you can ask the network administrator to run a scan across the network looking for misconfigured or infected devices.
Another way to prevent getting this page in the future is to use Privacy Pass. You may need to download version 2.0 now from the Chrome Web Store.
Cloudflare Ray ID: 71a83feb287691fc • Your IP : 82.102.23.104 • Performance & security by Cloudflare
![]()
Базовый вариант оформления input
- display: block – устанавливает блочное отображение;
- width: 100% – занимает всю доступную ширину;
- height: calc(2.25rem + 2px) – высота элемента определяется путём сложения 2.25rem ( font-size * line-height + padding-top + padding-bottom ) и 2px (ширина верхней и нижней границы);
- margin: 0 – убирает margin отступы;
- padding: 0.375rem 0.75rem – внутренние поля: сверху и снизу – 0.375rem, а слева и справа – 0.75rem;
- font-family: inherit – чтобы шрифт был такой как у родительского элемента, а не тот который браузер по умолчанию назначает для <input> ;
- font-size: 1rem – устанавливает явный размер шрифта, иначе будет браться из стилей браузера для <input> ;
- font-weight: 400 – задаёт начертание шрифта;
- line-height: 1.5 – высота строки (1.5 * размер шрифта);
- color: #212529 – цвет шрифта;
- background-color: #fff – цвет фона;
- background-clip: padding-box – указывает, что фон (фоновое изображение) нужно рисовать только до внешнего края отступа (под границей не выводить);
- border: 1px solid #bdbdbd – устанавливает границу, у которой: 1px (толщина), solid (тип линии) и #bdbdbd (цвет);
- border-radius: 0.25rem – радиус скругления углов;
- transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out – выполняет изменение значений свойств border-color и box-shadow с анимацией длительностью 0.15 секунд посредством временной функцией ease-in-out .




input с иконкой
input с активной svg-иконкой
input с кнопкой
input с плавающим label



input со счётчиком символов

Стили для отображения состояния валидации input




Пример валидации формы с помощью JavaScript
Put icon inside input element in a form

The site you linked uses a combination of CSS tricks to pull this off. First, it uses a background-image for the <input> element. Then, in order to push the cursor over, it uses padding-left .
In other words, they have these two CSS rules:
The CSS solutions posted by others are the best way to accomplish this.
If that should give you any problems (read IE6), you can also use a borderless input inside of a div.
Not as «clean», but should work on older browsers.
![]()
A solution without background-images:
Or for right to left icon
![]()
You can try this:
![]()
I find this the best and cleanest solution to it. Using text-indent on the input element:
A simple and easy way to position an Icon inside of an input is to use the position CSS property as shown in the code below. Note: I have simplified the code for clarity purposes.
- Create the container surrounding the input and icon.
- Set the container position as relative
- Set the icon as position absolute. This will position the icon relative to the surrounding container.
- Use either top, left, bottom, right to position the icon in the container.
- Set the padding inside the input so the text does not overlap the icon.
![]()
add above tags into your CSS file and use the specified class.
![]()
This works for me:
use this css class for your input at start, then customize accordingly:
![]()
I achieved this with the code below.
First, you flex the container which makes the input and the icon be on the same line. Aligning items makes them be on the same level.
Then, make the input take up 100% of the width regardless. Give the icon absolute positioning which allows it to overlap with the input.
Then add right padding to the input so the text typed in doesn’t get to the icon. And finally use the right css property to give the icon some space from the edge of the input.
Note: The Icon tag could be a real icon if you are working with ReactJs or a placeholder for any other way you work with icons in your project.
![]()
Just use the background property in your CSS.
![]()
I had situation like this. It didn’t work because of background: #ebebeb; . I wanted to put background on the input field and that property was constantly showing up on the top of the background image, and i couldn’t see the image! So, I moved the background property to be above the background-image property and it worked.
Solution for my case was:
Just to mention, border , padding and text-align properties are not important for the solution. I just replicated my original code.
![]()
Using with font-icon
For example you can use this : label with hidden input (icon is present).
![]()
I was able to add an icon to an input field by adding the icon as a background image through CSS. From there, you can adjust the size of the image using the background-size property and finally, position the element with the background-position-x and background-position-y properties. I’ve shared a code snippet below and linked to a working example in Codepen here:
I didn’t want to change the background of my input text neither it will work with my SVG icon.
What i did is adding negative margin to the icon so it appear inside the input box
and adding same value padding to the input so text won’t go under the icon.
*inline-style is for readability consider using classes
![]()
![]()
You could go for a different approach which also allows you to click it and have it do a function. Have a look at the example below:
The css background solutions do it for most cases, but it has a problem with webkit (chrome) autocomplete where the icon disappear.
There are other solutions that includes changing the html/dom structure by wrapping the input in a div and adding an extra element (img, div, or similar). I don’t like does solutions because you need to tweak the elements css with absolute positions and/or resizing by pixel to get the right place. Or recreate the input border to «merge» input and img in one.
So this solution is based on css background image not applied over input element, but applied over a wrapper div.
- This way with .input-email class I define my icon image as div background (not affected by webkit autocomplete background).
- Next .input-email input definition I pad left the input element to give space for the image and set it as transparent (this works when autocomplete is not applied)
- Finally with webkit-autofill classes I remove with transition the background-color set by the autocomplete.
Note: at point 2 I set transparent !important because this -internal-autofill-selected gets rendered at browser and I couldn’t overwrite it without setting my also as !important:
How TO — Form with Icons
Use a <form> element to process the input. You can learn more about this in our PHP tutorial. Then add inputs for each field:
Example
Step 2) Add CSS:
Example
/* Style the input container */
.input-container <
display: flex;
width: 100%;
margin-bottom: 15px;
>
/* Style the form icons */
.icon <
padding: 10px;
background: dodgerblue;
color: white;
min-width: 50px;
text-align: center;
>
/* Style the input fields */
.input-field <
width: 100%;
padding: 10px;
outline: none;
>
.input-field:focus <
border: 2px solid dodgerblue;
>
/* Set a style for the submit button */
.btn <
background-color: dodgerblue;
color: white;
padding: 15px 20px;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
>
Tip: Go to our HTML Form Tutorial to learn more about HTML Forms.
Tip: Go to our CSS Form Tutorial to learn more about how to style form elements.
Tip: Go to our CSS Flexbox Tutorial to learn more about the flexible box layout module.