Как поменять стиль input в css

от admin

CSS Forms

The look of an HTML form can be greatly improved with CSS:

Styling Input Fields

Use the width property to determine the width of the input field:

Example

The example above applies to all <input> elements. If you only want to style a specific input type, you can use attribute selectors:

  • input[type=text] — will only select text fields
  • input[type=password] — will only select password fields
  • input[type=number] — will only select number fields
  • etc..

Padded Inputs

Use the padding property to add space inside the text field.

Tip: When you have many inputs after each other, you might also want to add some margin , to add more space outside of them:

First Name Last Name

Example

Note that we have set the box-sizing property to border-box . This makes sure that the padding and eventually borders are included in the total width and height of the elements.
Read more about the box-sizing property in our CSS Box Sizing chapter.

Bordered Inputs

Use the border property to change the border size and color, and use the border-radius property to add rounded corners:

Example

If you only want a bottom border, use the border-bottom property:

Example

Colored Inputs

Use the background-color property to add a background color to the input, and the color property to change the text color:

Example

Focused Inputs

By default, some browsers will add a blue outline around the input when it gets focus (clicked on). You can remove this behavior by adding outline: none; to the input.

Use the :focus selector to do something with the input field when it gets focus:

Example

Example

Input with icon/image

If you want an icon inside the input, use the background-image property and position it with the background-position property. Also notice that we add a large left padding to reserve the space of the icon:

Example

Animated Search Input

In this example we use the CSS transition property to animate the width of the search input when it gets focus. You will learn more about the transition property later, in our CSS Transitions chapter.

Example

input[type=text] <
transition: width 0.4s ease-in-out;
>

input[type=text]:focus <
width: 100%;
>

Styling Textareas

Tip: Use the resize property to prevent textareas from being resized (disable the «grabber» in the bottom right corner):

Example

Styling Select Menus

Example

Styling Input Buttons

Example

input[type=button], input[type=submit], input[type=reset] <
background-color: #04AA6D;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
>

/* Tip: use width: 100% for full-width buttons */

For more information about how to style buttons with CSS, read our CSS Buttons Tutorial.

Responsive Form

Resize the browser window to see the effect. When the screen is less than 600px wide, make the two columns stack on top of each other instead of next to each other.

Advanced: The following example uses media queries to create a responsive form. You will learn more about this in a later chapter.

Aligned Form

An example of how to style labels together with inputs to create a horizontal aligned form:

Стилизация текстовых полей формы

В этой статье рассмотрим различные варианты стилизации текстовых полей 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 .

В результате получили следующее оформление:

Базовый вариант стилизации текстовых input

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

Стилизация плейсхолдера в input

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

Стилизация input в состоянии фокуса

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

Стилизация 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 с плавающим label

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

Пример оформления input с плавающим label

Пример оформления input с плавающим label

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

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

Пример оформления input со счётчиком символов

Это выполняется посредством следующего кода:

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

Применить стили в зависимости от состояния поля в CSS можно с помощью специальных псевдоклассов. Например, :valid позволяет выбрать валидные элементы, а :invalid — не валидные.

Но, если вы хотите контролировать этот процесс и добавлять стили с помощью JavaScript, то тогда лучше это делать через классы. Например, использовать класс text-field__input_valid при успешной валидации, а text-field__input_invalid — при не успешной. Их следует добавлять к <input> .

Отображать сообщения пользователю или подсказки можно через <div >. </div> .

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

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

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

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

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

Пример валидации формы с помощью JavaScript

Валидацию элементов формы будем осуществлять с помощью функции checkValidity() . После этого, в зависимости от её результата, будем добавлять той или иной класс к <input> , а также сообщение ( input.validationMessage ) в элемент .text-field__message .

Т.к. мы будем сами отображать сообщения, то необходимо отключить стандартные подсказки браузера. Для этого к тегу <form> необходимо добавить атрибут novalidate :

Styling web forms

In the previous few articles, we showed how to create web forms in HTML. Now, we’ll show how to style them in CSS.

Prerequisites: Basic computer literacy, and a basic understanding of HTML and CSS.
Objective: To understand the issues behind styling forms, and learn some of the basic styling techniques that will be useful to you.

Challenges in styling form widgets

History

In 1995, the HTML 2 specification introduced form controls (a.k.a. «form widgets», or «form elements»). But CSS wasn’t released until late 1996, and wasn’t supported by most browsers until years afterward; so, in the interim, browsers relied on the underlying operating system to render form widgets.

Even with CSS available, browser vendors were reluctant at first to make form elements stylable, because users were so accustomed to the looks of their respective browsers. But things have changed, and forms widgets are now mostly stylable, with a few exceptions.

Types of widgets

Easy-to-style
Harder-to-style
  • Checkboxes and radio buttons

The article Advanced form styling shows how to style these.

Having internals can’t be styled in CSS alone

For example, the date picker calendar, and the button on <select> that displays an options list when clicked, can’t be styled using CSS alone.

The articles Advanced form styling and How to build custom form controls describe how to style these.

Note: some proprietary CSS pseudo-elements, such as ::-moz-range-track , are capable of styling such internal components, but these aren’t consistent across browsers, so aren’t very reliable. We will mention these later.

Styling simple form widgets

The «easy-to-style» widgets in the previous section may be styled using techniques from the articles Your first form and CSS building blocks. There are also special selectors — UI pseudo-classes — that enable styling based on the current state of the UI.

We’ll walk through an example at the end of this article — but first, here are some special aspects of form styling that are worth knowing about.

Fonts and text

CSS font and text features can be used easily with any widget (and yes, you can use @font-face with form widgets). However, browser behavior is often inconsistent. By default, some widgets do not inherit font-family and font-size from their parents. Many browsers use the system’s default appearance instead. To make your forms’ appearance consistent with the rest of your content, you can add the following rules to your stylesheet:

The inherit property value causes the property value to match the computed value of the property of its parent element; inheriting the value of the parent.

The screenshots below show the difference. On the left is the default rendering of an <input type=»text»> , <input type=»date»> , <select> , <textarea> , <input type=»submit»> , and a <button> in Chrome on macOS, with the platform’s default font style in use. On the right are the same elements, with our above style rule applied.

Form controls with default and inherited font families. By default, some types are serif and others are sans serif. Inheriting should change the fonts of all to the parent

The defaults differed in a number of ways. Inheriting should change their fonts to that of the parent’s font family — in this case, the default serif font of the parent container. They all do, with a strange exception — <input type=»submit»> does not inherit from the parent paragraph in Chrome. Rather, it uses the font-family: system-ui . This is another reason to use <button> elements over their equivalent input types!

There’s a lot of debate as to whether forms look better using the system default styles, or customized styles designed to match your content. This decision is yours to make, as the designer of your site, or web application.

Box sizing

All text fields have complete support for every property related to the CSS box model, such as width , height , padding , margin , and border . As before, however, browsers rely on the system default styles when displaying these widgets. It’s up to you to define how you wish to blend them into your content. If you want to keep the native look and feel of the widgets, you’ll face a little difficulty if you want to give them a consistent size.

This is because each widget has its own rules for border, padding, and margin. To give the same size to several different widgets, you can use the box-sizing property along with some consistent values for other properties:

In the screenshot below, the left column shows the default rendering of an <input type=»radio»>, <input type=»checkbox»>, <input type=»range»>, <input type=»text»>, <input type=»date»> input, <select> , <textarea> ,<input type=»submit»>, and <button> . The right column on the other hand shows the same elements with our above rule applied to them. Notice how this lets us ensure that all of the elements occupy the same amount of space, despite the platform’s default rules for each kind of widget.

box model properties effect most input types.

What may not be apparent via the screenshot is that the radio and checkbox controls still look the same, but they are centered in the 150px of horizontal space provided by the width property. Other browsers may not center the widgets, but they do adhere to the space allotted.

Legend placement

The <legend> element is okay to style, but it can be a bit tricky to control the placement of it. By default, it is always positioned over the top border of its <fieldset> parent, near the top left corner. To position it somewhere else, for example inside the fieldset somewhere, or near the bottom left corner, you need to rely on the positioning.

Take the following example:

To position the legend in this manner, we used the following CSS (other declarations removed for brevity):

The <fieldset> needs to be positioned too, so that the <legend> is positioned relative to it (otherwise the <legend> would be positioned relative to the <body> ).

The <legend> element is very important for accessibility — it will be spoken by assistive technologies as part of the label of each form element inside the fieldset — but using a technique like the one above is fine. The legend contents will still be spoken in the same way; it is just the visual position that has changed.

Note: You could also use the transform property to help you with positioning your <legend> . However, when you position it with for example a transform: translateY(); , it moves but leaves an ugly gap in the <fieldset> border, which is not easy to get rid of.

A specific styling example

Let’s look at a concrete example of how to style an HTML form. We will build a fancy-looking «postcard» contact form; see here for the finished version.

If you want to follow along with this example, make a local copy of our postcard-start.html file, and follow the below instructions.

The HTML

The HTML is only slightly more involved than the example we used in the first article of this guide; it just has a few extra IDs and a heading.

Add the above code into the body of your HTML.

Organizing your assets

This is where the fun begins! Before we start coding, we need three additional assets:

    — download this image and save it in the same directory as your working HTML file.
  1. A typewriter font: The «Mom’s Typewriter» font from dafont.com — download the TTF file into the same directory as above.
  2. A hand-drawn font: The «Journal» font from dafont.com — download the TTF file into the same directory as above.

Your fonts need some more processing before you start:

  1. Go to the fontsquirrel.com Webfont Generator.
  2. Using the form, upload both your font files and generate a webfont kit. Download the kit to your computer.
  3. Unzip the provided zip file.
  4. Inside the unzipped contents you will find some font files (at the time of writing, two .woff files and two .woff2 files; they might vary in the future.) Copy these files into a directory called fonts, in the same directory as before. We are using two different files for each font to maximize browser compatibility; see our Web fonts article for a lot more information.
Читать:
Найдите математическое ожидание дискретной случайной величины которая задана законом распределения

The CSS

Now we can dig into the CSS for the example. Add all the code blocks shown below inside the <style> element, one after another.

Overall layout

First, we prepare by defining our @font-face rules, and all the basic styles set on the <body> and <form> elements. If the fontsquirrel output was different from what we described above, you can find the correct @font-face blocks inside your downloaded webfont kit, in the stylesheet.css file (you’ll need to replace the below @font-face blocks with them, and update the paths to the font files):

Notice that we’ve used some CSS Grid and Flexbox to lay out the form. Using this we can easily position our elements, including the title and all the form elements:

Labels and controls

Now we can start working on the form elements themselves. First, let’s ensure that the <label> s are given the right font:

The text fields require some common rules. In other words, we remove their borders and backgrounds , and redefine their padding and margin :

When one of these fields gains focus, we highlight them with a light grey, transparent, background (it is always important to have focus style, for usability and keyboard accessibility):

Now that our text fields are complete, we need to adjust the display of the single and multiple-line text fields to match, since they won’t typically look the same using the defaults.

Tweaking the textareas

<textarea> elements default to being rendered as an inline-block element. The two important things here are the resize and overflow properties. While our design is a fixed-size design, and we could use the resize property to prevent users from resizing our multi-line text field, it is best to not prevent users from resizing a textarea if they so choose. The overflow property is used to make the field render more consistently across browsers. Some browsers default to the value auto , while some default to the value scroll . In our case, it’s better to be sure everyone will use auto :

Styling the submit button

The <button> element is really convenient to style with CSS; you can do whatever you want, even using pseudo-elements:

The final result

And voilà! Your form should now look like this:

The final look and layout of the form after applying all styling and tweaking to it as described above

Note: If your example does not work quite as you expected and you want to check it against our version, you can find it on GitHub — see it running live (also see the source code).

Test your skills

You’ve reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you’ve retained this information before you move on — see Test your skills: Styling basics.

Summary

As you can see, as long as we want to build forms with just text fields and buttons, it’s easy to style them using CSS. In the next article, we will see how to handle form widgets which fall into the «bad» and «ugly» categories.

Custom CSS Styles for Form Inputs and Textareas

This is episode #21 in a series examining modern CSS solutions to problems Stephanie Eckles has been solving over the last 14+ years as a front-end dev.

Table of Contents

We’re going to create custom form input and textarea styles that have a near-identical appearance across the top browsers. We’ll specifically style the input types of text , date , and file , and style the readonly and disabled states.

Read on to learn how to:

  • reset input styles
  • use hsl for theming of input states
  • ensure all states meet contrast requirements
  • retain a perceivable :focus state for Windows High Contrast mode

Now available: my egghead video course Accessible Cross-Browser CSS Form Styling. You’ll learn to take the techniques described in this tutorial to the next level by creating a themable form design system to extend across your projects.

This is the fourth installment in the Modern CSS form field mini-series. Check out episodes 18-20 to learn how to style other common form field types including radio buttons, checkboxes, and selects.

Common Issues with Native Input Styles

There is a bit more parity between text input styles than we saw with radios, checkboxes, and selects, but inconsistencies nonetheless.

Here’s a screenshot of the unstyled inputs we’re going to address today across (from left) Chrome, Safari, and Firefox.

native input fields including text, date, file, and readonly and disabled states in the aforementioned browsers

We will be looking to unify the initial appearance across browsers and common field types.

The date field is unique in that Chrome and Firefox provide formatting and a popup calendar to select from, while Safari offers no comparable functionality. We cannot create this in CSS either, so our goal here is to get as far as we can with creating a similar initial appearance. Check out the caniuse for date/time inputs.

Base HTML

We’re covering a lot of field types, so check the CodePen for the full list. But here is the essential HTML for a text input and a textarea.

To allow simplifying our styles and preparing to work with the cascade, we’ve only added one CSS class — input — which is placed directly on the text input and textarea.

The label is not part of our styling exercise, but its included as a general requirement, notably with the for attribute having the value of the id on the input.

Create CSS Variables for Theming

For the tutorial, we’re going to try a bit different technique for theming by using hsl values.

We’ll set a grey for the border, and then break down a blue color to be used in our :focus state into its hsl values, including: h for "hue", s for "saturation", and l for "lightness".

Each of the tutorials for our form fields has incorporated a bit different method for theming, which can all be extracted and used beyond just forms!

Accessible Contrast

As per all user interface elements, the input border needs to have at least 3:1 contrast against it’s surroundings.

And, the :focus state needs to have 3:1 contrast against the unfocused state if it involves something like changing the border color or, according to the WCAG 2.2 draft, a thickness greater than or equal to 2px .

The draft for WCAG 2.2 makes some slight adjustments to :focus requirements, and I encourage you to review them.

Reset Styles

As is included in all my tutorials as a modern best practice, we add the following reset first:

As seen in the initial state of the fields across browsers, some standout differences were in border type, background color, and font properties.

Interestingly, font-size and font-family do not inherit from the document like typography elements do, so we need to explicitly set them as part of our reset.

Also of note, an input’s font-size should compute to at least 16px to avoid zooming being triggered upon interaction in mobile Safari. We can typically assume 1rem equals 16px , but we’ll explicitly set it as a fallback and then use the newer CSS function max to set 16px as the minimum in case it’s smaller than 1em (h/t to Dan Burzo for this idea).

We set our border to use the theme variable, and also created a slightly rounded corner.

After this update, we’re already looking pretty good:

updated input styles in Chrome, Safari, and Firefox which all show the inputs with unified grey borders and white backgrounds

It may be difficult to notice in that screenshot, but another difference is the height of each field. Here’s a comparison of the text input to the file input to better see this difference:

text input field across browsers compared to file input

Let’s address this with the following which we are applying to our .input class as long as it is not placed on a textarea :

We included line-height: 1 since when it’s not a textarea it’s impossible for an input to be multiline. We also set our height in rem due to considerations of specifically the file input type. If you know you will not be using a file input type, you could use em here instead for flexibility in creating various sized inputs.

But, critically, we’ve lost differentiation between editable and disabled input types. We also want to define readonly with more of a hint that it’s also un-editable, but still interactive. And we have a bit more work to do to smooth over the file input type. And, we want to create our themed :focus state.

Join my newsletter for article updates, CSS tips, and front-end resources!

File Input CSS

Let’s take another look at just our file input across Chrome, Safari, and Firefox:

current state of the file input styling across browsers

We cannot style the button created by the browser, or change the prompt text, but the reset we provided so far did do a bit of work to allow our custom font to be used.

We’ll make one more adjustment to downsize the font just a bit as when viewed with other field types the inherited button seems quite large, and font-size is our only remaining option to address it. From doing that, we need to adjust the top padding since we set our padding up to be based on em .

If you were expecting a fancier solution, there are plenty of folx who have covered those. My goal here was to provide you a baseline that you can then build from.

readonly CSS Style

While not in use often, the readonly attribute prevents additional user input, although the value can be selected, and it is still discoverable by assistive tech.

Let’s add some styles to enable more of a hint that this field is essentially a placeholder for a previously entered value.

To do this, we’ll target any .input that also has the [readonly] attriute. Attribute selectors are a very handy method with wide application, and definitely worth adding to (or updating your awareness of) in your CSS toolbox.

In addition to swapping for a dotted border, we’ve also assigned it the not-allowed cursor and enforced a medium-grey text color.

As seen in the following gif, the user cannot interact with the field except to highlight/copy the value.

Disabled Input and Textarea Style

Similar to readonly , we’ll use an attribute selector to update the style for disabled fields. We are attaching it to the .input class so it applies on textareas as well as our other input types.

We’ll make use of our CSS variable to update the border color to a muted grey, and the field background to a very light grey. We’ll also again apply the not-allowed cursor as just an extra hint that the field is not interactive.

And here is the result for both a text input and a textarea:

Alt Text

Accessibility Note: disabled fields are not necessarily discoverable by assistive tech since they are not focusable. They also are not required to meet even the typical 3:1 contrast threshold for user interface elements, but we’ve kept with user expectations by setting them to shades of grey.

Textarea Styles

Our textarea is really close, but there’s one property I want to mention since it’s unique to the inherent behavior of textareas.

That property is resize , which allows you to specify which direction the textarea can be resized, or if it even can at all.

While you definitely should allow the textarea to retain the resize function under general circumstances, you can limit it to just vertical resizing to prevent layout breakage from a user dragging it really wide, for example.

We’ll apply this property by scoping our .input class to when it’s applied on a textarea :

Try it out in the final CodePen demo!

:focus State Styles

Ok, we’ve completed the initial styles for our inputs and the textarea, but we need to handle for a very important state: :focus .

We’re going to go for a combo effect that changes the border color to a value that meets 3:1 contrast against the unfocused state, but also adds a box-shadow for a bit of extra highlighting.

And here’s why we defined our theme color of the focus state in hsl: it means we can create a variant of the border color by updating just the lightness value.

First, we define the border color by constructing the full hsl value from the individual CSS variable values:

Then, we add in the box-shadow which will only use blur to create essentially a double-border effect. calc() is acceptable to use inside hsla , so we use it to lighten the original value by 40%, and also allow just a bit of alpha transparency:

Note that we’ve now added a new context for our contrast, which is the :focus border vs. the :focus box-shadow , so ensure the computed difference for your chosen colors is at least 3:1 if using this method.

Optionally, jump back up to the .input rule and add a transition to animate the box-shadow :

Finally, we don’t want to forget Windows High Contrast mode which will not see the box-shadow or be able to detect the border color change. So, we include a transparent outline for those users:

We also use this technique in the episode covering button styles.

Here’s a gif demo of focusing into the text input:

And here’s the appearance for the readonly field, since it has a different border-style :

the readonly field when focused

In the CodePen HTML, there is a comment with an example of using an inline style to define an updated visual such as for an error state. Again, keep in mind that we are lightening the provided —input-focus-l value by 40%, and the focused border color must be at least 3:1 contrast against the unfocused color, so consider that when you alter the CSS variable values.

Input Mode and Autocomplete

There are two aditional attributes that can help improve the user experience, particularly on mobile, in addition to using the correct input type (ex: email).

The first is defining the inputmode , which provides an altered keyboard or keypad that better matches the expected data. Read up on available inputmode values on MDN >

Second is autocomplete which has far more options than on or off . For example, I always appreciate that on iPhone when Google sends me a confirmation code by text the keyboard "just knows" what that value is. Turns out, that’s thanks to autocomplete="one-time-code" !

Check out the full list of autocomplete values that allow you to hint at the value expected and really boost the user experience of your forms for users that make use of auto-filling values.

First, here’s a final look at our solution across (from left) Chrome, Safari, and Firefox. The file input still sticks out a bit when viewed side by side, but in the flow of a form on an individual browser it’s definitely acceptable.

final input and textarea styles across the aforementioned browsers

Here is the solution with all the field types we covered represented.

By Stephanie Eckles (@5t3ph)

What to Read Next

"Back to top" links may not be in use often these days, but there are two modern CSS features that the technique demonstrates well: `position: sticky` and `scroll-behavior: smooth`.

This guide will build on the previous episode 'CSS Button Styling Guide' to explore the use case of icon buttons. We'll cover icon + text as well as icon-only buttons.

Join my newsletter for article updates, CSS tips, and front-end resources!

Whether you choose to completely write your own CSS, or use a framework, understanding selectors, the cascade, and specificity are critical to developing CSS and modifying existing style rules.

Похожие статьи