поиск
На сайтах часто востребован поиск по ключевым словам, для ввода которых используется текстовое поле. В HTML5 для поиска добавлено новое поле, синтаксис его следующий:
Используемые атрибуты совпадают с текстовым полем.
Добавление предложений в поисковый плагин
Поисковик Google был один из первых, кто добавил к своему поиску предложение популярных запросов — вы набираете текст и сразу же получаете список слов начинающихся с введенных символов. В дальнейшем эта технология стала настолько популярна, что теперь ее можно встретить повсеместно. Также она включена и в спецификацию OpenSearch, на основе которой работает поисковый плагин для браузера.
Поиск по сайту через Google и Яндекс
Поиск на сайте, где много информации, это один из способов отыскать и прочитать нужный материал. Эта мысль настолько очевидна, что никакого подтверждения не требует, поэтому практически во все системы управления сайтом поиск вставлен по умолчанию. Как быть, если подобный поиск по каким-либо причинам не устраивает или вообще отсутствует? Позаимствовать систему поиска у Google или Яндекса. И у той и другой компании есть прекрасные средства для организации поиска по одному или нескольким ресурсам.
Поисковый плагин для сайта
В интерфейс браузера Firefox, начиная с версии 2.0 встроена строка поиска, позволяющая без захода на сайт вводить поисковые запросы к Гуглу, Яндексу и другим системам. Идея оказалась удачной и ее впоследствии подхватили разработчики других браузеров. Несмотря на то, что подобным поиском пользуются многие, включая и создателей сайтов, большинство из них не подозревают, насколько просто и легко сделать собственный поисковый плагин для сайта. Плюсов у такого плагина несколько: пользователи начинают активнее использовать поиск, возрастает количество посетителей, повышается результативность сайта, улучшается юзабилити. Главное, что затрат практически нет. Если на сайте используется поиск, «прикрутить» для него плагин раз плюнуть.
Пример верстки поисковой формы для сайта на HTML5 и CSS3
После публикации вчерашней статьи по верстке поисковой формы меня раскритиковали, мол верстка отстой, есть же современные HTML5 и CSS3. Я, конечно, понимаю, последние стандарты это круто и все такое. Но дело в том, что верстаю я, как правило, под заказ, а там в большинстве случаев важна полная идентичность в разных браузерах, что не позволяет использовать последние технологии. Поэтому я ориентируюсь в первую очередь на кроссбраузерность и поисковую форму по привычке сверстал «по-старому». В общем, этим постом исправляю ситуацию (в угоду недовольным прошлой статьей =) и предлагаю свой вариант верстки той же самой поисковой формы, но уже с использованием технологий HTML5 и CSS3. Пример того, что получится в результате, можно увидеть здесь.
Что мы теряем при верстке данной формы с помощью HTML5 и CSS3
- IE9 и ниже — не увидим текст по умолчанию (атрибут placeholder ).
- IE8 и ниже — не увидим закругленных углов и внутренних теней.
- IE7 — для него приходится указать другую ширину формы, т.к. он не поддерживает свойство box-sizing .
- IE6 — а его вообще в расчет не берем =)
В остальных современных браузерах все замечательно. Я считаю, что вышеуказанные недостатки не критичны, поэтому для своего сайта я бы смело использовал форму, сверстанную по последним технологиям.
HTML-код формы поиска
Выглядит он вот так:
По сравнению с формой из предыдущей статьи здесь внесены следующее изменения в соответствии с технологией HTML5:
И стили для IE ниже 9-й версии:
/* задаем отдельные стили для браузеров IE ниже 9-й версии */ *+html .search < /* для IE7 подгоняем ширину под другие браузеры и добавляем правый ** внутренний отступ, чтобы кнопка отправки встала на свое место */ width: 28%; padding: 0 52px 0 0; >.search .input < border: 1px solid #DFDFDF; border-top: 1px solid #B3B3B3; padding-top: 7px; padding-bottom: 8px; >.search .input:focus < border: 1px solid #CFCFCF; border-top: 1px solid #999; >.search .submit < filter: alpha(opacity=50); >.search .submit:hover
P.S. Спасибо критикам за комментарии к предыдущей статье! Благодаря вам, у меня в голове отложились некоторые новые для меня моменты по верстке.
Смотрите также

Пример верстки поисковой формы для сайта
56 комментариев
Предлагаю один из возможных вариантов верстки поисковой формы для сайта, которая будет выглядеть вот так: Ее особенность заключается в том, что вся видимая часть формы — это поле ввода текста и нужно учесть, что его .

Верстка красивых тегов для сайта + бонус
25 комментариев
Замечательный дизайнер Orman Clark однажды представил своим читателям очень красивый дизайн облака тегов, который я использовал на одном моем сайте. Расскажу, как сверстать такие теги для вашего сайта. Для начала необходимо приготовить .

Зеленый свет CSS-свойствам при верстке под IE8 и выше
26 комментариев
Пришло время, и я наконец-таки решился отказаться от верстки под устаревший браузер Internet Explorer 7. Если это будет верстка на заказ, то вносить изменения под него буду только за дополнительную плату, а для своих проектов забуду вообще. .

Эмуляция псевдо-селектора :nth-child () в IE7 и IE8
13 комментариев
Неоднократно при верстке сайтов мне приходилось сталкиваться с ситуацией, когда строки в таблице или пункты вертикального списка необходимо было оформить зеброй. Т. е. одна строка, к примеру, с белым фоном, вторая с серым, третья опять .
Как создать поле поиска
Поля поиска распространены на каждой веб-странице. Они очень полезны при поиске конкретной информации. Поле поиска может иметь функцию ввода с автодополнением, что помогает пользователям при поиске.
В этой статье мы пошагово покажем, как можно создать поле поиска с помощью CSS и HTML.
- Создайте HTML
- Создайте тег , который используется для добавления HTML форм к веб-странице для пользовательского ввода.
- Добавьте тег внутри элемента .
- Добавьте также placeholder с выражением «Search here!» и класс «Search».
- Добавьте другой input c классом «submit» и значение «search». ска, используя только CSS и HTML.
form> input type="text" name=text" placeholder"Search here!"> input type="submit" name="submit" value="Search"> form>
Теперь у нас есть поле поиска, но необходимо добавить стиль.
Есть три элемента, к которым необходимо применить стиль: «form», «search» и»submit».
- Добавьте фоновый цвет текстовой части (body).
- Начните оформление классов «form», «search»и «submit».
- Установите width, margin, padding, и font-size.
После того, как все свойства добавлены, запустите код и увидите результат!
Пример
html> html> head> title>Заголовок документа title> style> body < background-color: #8ebf42; > form < width:400px; margin:auto; margin-top: 250px; > input< padding:4px 10px; border:0; font-size:16px; > .search < width: 75%; > .submit< width: 70px; background-color: #1c87c9; color:#ffffff; > style> head> body> h2>Создайте поле поиска h2> form> input type="text" name=text" class="search" placeholder"Search here!"> input type="submit" name="submit" class="submit" value="Search"> form> body> html>
Давайте создадим другие поля поиска:
Пример
html> html> head> link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> title>Поле поиска title> style> body < margin: 0; padding: 0; background: #00a08d; > .search-box < position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #666666; height: 40px; border-radius: 40px; padding: 10px; > .search-box:hover > .search-txt < width: 240px; padding: 0 6px; > .search-box:hover > .search-btn < background: white; color: black; > .search-btn < color: #eeeeee; float: right; width: 40px; height: 40px; border-radius: 50%; background: #2f3640; display: flex; justify-content: center; align-items: center; transition: 0.4s; color: white; cursor: pointer; text-decoration:none; > .search-btn > i < font-size: 20px; > .search-txt < border: none; background: none; outline: none; float: left; padding: 0; color: white; font-size: 16px; transition: 0.4s; line-height: 40px; width: 0px; font-weight: bold; > > style> head> body> div class="search-box"> input type="text" name="" class="search-txt" placeholder="Type to search"/> a class="search-btn" href="#"> i class="fa fa-search" aria-hidden="true"> i> a> div> body> html>
В данном примере мы использовали Search icon из Fontawesome.
Другой пример, где использованы только HTML и CSS:
Пример
html> html> head> link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> title>Заголовок документа title> style> body< background: #cccccc; > .search < width: 100%; position: relative; display: flex; > .searchTerm < width: 100%; border: 3px solid #9e0098; border-right: none; padding: 5px; height: 20px; border-radius: 5px 0 0 5px; outline: none; > .searchTerm:focus< color: #380136; > .searchButton < width: 40px; height: 36px; border: 1px solid #9e0098; background: #9e0098; text-align: center; color: #eeeeee; border-radius: 0 5px 5px 0; cursor: pointer; font-size: 20px; > .wrap< width: 30%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); > style> head> body> h2>Создайте поле поиска h2> div class="wrap"> div class="search"> input type="text" class="searchTerm" placeholder="Type"> button type="submit" class="searchButton"> i class="fa fa-search"> i> button> div> div> body> html>
Рассмотрим еще один пример создания поля поиска:
Пример
html> html> head> title>Заголовок документа title> style> *, *::after, *::before < margin: 0; padding: 0; box-sizing: inherit; > html < font-size: 50%; > body < box-sizing: border-box; > .container < width: 25rem; height: 100%; margin: 0 1rem; position: relative; > h2 < margin: 2rem; font-size: 20px; > .searchbar < font-size: 2.4rem; width: 25rem; height: 5rem; border: none; outline: none; border-radius: 10rem; padding: 2rem; transition: all .1s; transition-delay: .1s; > .searchbar:hover < width: 27rem; height: 6rem; > .button < height: 2rem; position: absolute; top: 1.5rem; right: 1rem; transition: all .1s; transition-delay: .1s; > .button:hover < cursor: pointer; > .searchbar:hover + .button < height: 2.5rem; top: 1.8rem; right: 0; > .searchbar::placeholder < opacity: .3; > style> head> body> h2>Создайте поле поиска h2> div class="container"> input type="text" maxlength= "12" placeholder="Search" class="searchbar"> img src="https://images-na.ssl-images-amazon.com/images/I/41gYkruZM2L.png" alt="search icon" class="button"> div> body> html>
Как отредактировать поисковик через css
элементы с типом search это текстовые поля разработанные для ввода пользователем поисковых запросов. Функциональность идентична элементам с типом text , но может отличаться стилизация за счёт user agent, а также наличием специального не стандартизированного события onsearch .
| Value | A DOMString representing the value contained in the search field. |
| Events | change (en-US) and input (en-US) |
| Supported Common Attributes | autocomplete , list , maxlength , minlength , pattern , placeholder , required , size . |
| IDL attributes | value |
| Methods | select() (en-US), setRangeText() (en-US), setSelectionRange() . |
Value
The value attribute contains a DOMString representing the value contained in the search field. You can retrieve this using the HTMLInputElement.value property in JavaScript.
If no validation constraints are in place for the input (see Validation for more details), the value can be any text string or an empty string ( «» ).
Additional attributes
In addition to the attributes that operate on all elements regardless of their type, search field inputs support the following attributes:
| Attribute | Description |
|---|---|
| list | The id of the element that contains the optional pre-defined autocomplete options |
| maxlength | The maximum number of characters the input should accept |
| minlength | The minimum number of characters long the input can be and still be considered valid |
| pattern | A regular expression the input’s contents must match in order to be valid |
| placeholder | An exemplar value to display in the input field whenever it is empty |
| readonly | A Boolean attribute indicating whether or not the contents of the input should be read-only |
| size | A number indicating how many characters wide the input field should be |
| spellcheck | Controls whether or not to enable spell checking for the input field, or if the default spell checking configuration should be used |
The values of the list attribute is the id of a element located in the same document. The provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.
maxlength
The maximum number of characters (as UTF-16 code units) the user can enter into the search field. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the search field has no maximum length. This value must also be greater than or equal to the value of minlength .
The input will fail constraint validation if the length of the text entered into the field is greater than maxlength UTF-16 code units long.
minlength
The minimum number of characters (as UTF-16 code units) the user can enter into the search field. This must be a non-negative integer value smaller than or equal to the value specified by maxlength . If no minlength is specified, or an invalid value is specified, the search input has no minimum length.
The search field will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long.
pattern
See the section Specifying a pattern for details and an example.
placeholder
The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds.
If the control’s content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see How to use Unicode controls for bidi text for more information.
Note: Avoid using the placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Placeholders are not accessible in : The Input (Form Input) element for more information.
readonly
A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by JavaScript code directly setting the HTMLInputElement value property.
Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified.
The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ( font settings in use).
This does not set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the maxlength attribute.
spellcheck
Non-standard attributes
The following non-standard attributes are available to search input fields. As a general rule, you should avoid using them unless it can’t be helped.
| Attribute | Description |
|---|---|
| autocorrect | Whether or not to allow autocorrect while editing this input field. Safari only. |
| incremental | Whether or not to send repeated search events to allow updating live search results while the user is still editing the value of the field. WebKit and Blink only (Safari, Chrome, Opera, etc.). |
| mozactionhint | A string indicating the type of action that will be taken when the user presses the Enter or Return key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. Firefox for Android only. |
| results | The maximum number of items that should be displayed in the drop-down list of previous search queries. Safari only. |
autocorrect Non-Standard
incremental Non-Standard
The Boolean attribute incremental is a WebKit and Blink extension (so supported by Safari, Opera, Chrome, etc.) which, if present, tells the user agent to process the input as a live search. As the user edits the value of the field, the user agent sends search events to the HTMLInputElement object representing the search box. This allows your code to update the search results in real time as the user edits the search.
If incremental is not specified, the search event is only sent when the user explicitly initiates a search (such as by pressing the Enter or Return key while editing the field).
The search event is rate-limited so that it is not sent more more frequently than an implementation-defined interval.
mozactionhint Non-Standard
results Non-Standard
The results attribute—supported only by Safari—is a numeric value that lets you override the maximum number of entries to be displayed in the element’s natively-provided drop-down menu of previous search queries.
The value must be a non-negative decimal number. If not provided, or an invalid value is given, the browser’s default maximum number of entries is used.
Using search inputs
elements of type search are very similar to those of type text , except that they are specifically intended for handling search terms. They are basically equivalent in behavior, but user agents may choose to style them differently by default (and, of course, sites may use stylesheets to apply custom styles to them).
Basic example
This renders like so:
q is the most common name given to search inputs, although it’s not mandatory. When submitted, the data name/value pair sent to the server will be q=searchterm .
You must remember to set a name for your input, otherwise nothing will be submitted.
Differences between search and text types
The main basic differences come in the way browsers handle them. The first thing to note is that some browsers show a cross icon that can be clicked on to remove the search term instantly if desired. The following screenshot comes from Chrome:
In addition, modern browsers also tend to automatically store search terms previously entered across domains, which then come up as autocomplete options when subsequent searches are performed in search inputs on that domain. This helps users who tend to do searches on the same or similar search queries over time. This screenshot is from Firefox:

At this point, let’s look at some useful techniques you can apply to your search forms.
Setting placeholders
You can provide a useful placeholder inside your search input that could give a hint on what to do using the placeholder attribute. Look at the following example:
You can see how the placeholder is rendered below:
Search form labels and accessibility
One problem with search forms is their accessibility; a common design practice is not to provide a label for the search field (although there might be a magnifying glass icon or similar), as the purpose of a search form is normally fairly obvious for sighted users due to placement (this example shows a typical pattern).
This could, however, cause confusion for screenreader users, since they will not have any verbal indication of what the search input is. One way around this that won’t impact on your visual design is to use WAI-ARIA features:
- A role attribute of value search on the element will cause screenreaders to announce that the form is a search form.
- If that isn’t enough, you can use an aria-label attribute on the itself. This should be a descriptive text label that will be read out by the screenreader; it’s used as a non-visual equivalent to .
Let’s have a look at an example:
You can see how this is rendered below:
There is no visual difference from the previous example, but screenreader users have way more information available to them.
Note: See Signposts/Landmarks for more information about such accessibility features.
Physical input element size
The physical size of the input box can be controlled using the size attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the search box is 30 characters wide:
The result is this wider input box:
Validation
elements of type search have the same validation features available to them as regular text inputs. It is less likely that you’d want to use validation features in general for search boxes. In many cases, users should just be allowed to search for anything, but there are a few cases to consider, such as searches against data of a known format.
Note: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It’s far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It’s also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database.
A note on styling
There are useful pseudo-classes available for styling valid/invalid form elements: :valid and :invalid . In this section, we’ll use the following CSS, which will place a check (tick) next to inputs containing valid values, and a cross next to inputs containing invalid values.
The technique also requires a element to be placed after the form element, which acts as a holder for the icons. This was necessary because some input types on some browsers don’t display icons placed directly after them very well.
Making input required
You can use the required attribute as an easy way of making entering a value required before form submission is allowed:
This renders like so:
In addition, if you try to submit the form with no search term entered into it, the browser will show a message. The following example is from Firefox:

Different messages will be shown when you try to submit the form with different types of invalid data contained inside the inputs; see the below examples.
Input value length
You can specify a minimum length, in characters, for the entered value using the minlength attribute; similarly, use maxlength to set the maximum length of the entered value.
The example below requires that the entered value be 4–8 characters in length.
This renders like so:
If you try to submit the form with less than 4 characters, you’ll be given an appropriate error message (which differs between browsers). If you try to go beyond 8 characters in length, the browser won’t let you.
Specifying a pattern
You can use the pattern attribute to specify a regular expression that the inputted value must follow to be considered valid (see Validating against a regular expression for a simple crash course).
Let’s look at an example. Say we wanted to provide a product ID search form, and the IDs were all codes of two letters followed by four numbers. The following example covers it:
This renders like so:
Examples
You can see a good example of a search form used in context at our website-aria-roles example (see it live).
Форма поиска по сайту
Если набрать в поле «вопрос» и щелкнуть по кнопке «Найти», то адрес страницы изменится с « http://shpargalkablog.ru/2011/06/forma-poiska-po-saitu.html » на « http://shpargalkablog.ru/2011/06/forma-poiska-po-saitu.html?text=вопрос », как это происходит при нажатии на ссылку. При загрузке страницы, скрипт проверяет наличие заданных параметров в URL и при их обнаружении формирует и отображает результаты поиска по сайту.
Но в целях увеличения скорости загрузки документа, скрипт, обрабатывающий запрос, как правило, помещают только на одну страницу сайта, на которую будет сделан переход, если её адрес прописать в атрибуте action : « http://shpargalkablog.ru/search/?text=вопрос ».
Для работы скрипта могут понадобиться дополнительные параметры, которые указываются в . Это поле не отображается. Теперь форма будет вызывать « http://shpargalkablog.ru/search/?searchid=808327&text=вопрос ».
Результат работы формы открыть в новой вкладке с помощью атрибута target
Где взять скрипт поиска по сайту
- предложенным специальными сервисами Яндекса и Google,
- встроенным в используемую CMS (при наличии), например, на Blogger на « https://site.ru/search?q=вопрос », где « site.ru » заменить на свой адрес блога,
- разработанным самостоятельно, например, на PHP.
Самый простой вариант — перенаправить запрос Google:
Текст на кнопке: «Поиск», «Искать», «Найти»
Из слов-побудителей «Найти» имеет совершённый вид и подразумевает, что результат поиска будет обязательно положительным.
Как сделать поиск по сайту на HTML

На этом уроке мы научимся встраивать строку поиска в адаптивное меню навигации, используя при этом только HTML/CSS код.
Демонстрация примера.
HTML разметка
Внутри меню навигации у нас будет три пункта меню в виде ссылок и встроен блок с классом search-box, внутри которого форма для поиска с полем поиска и кнопкой.
Вся эта конструкция до стилизации выглядит таким вот образом.

CSS код
Зададим светло-зелёный цвет фона для панели навигации.
Поместим все ссылки в строку с помощью обтекания слева, представим ссылки, как изначально строчные элементы – блочными.
Меняем цвет фона под ссылками при наведении.
Стилизуем активный элемент для выделения пункта меню текущей страницы.
Располагаем контейнер для поиска на правой части панели навигации.
Стилизуем поле для поиска внутри панели навигации.
Стилизуем кнопку Отправить внутри контейнера с поиском, располагая её правее по отношению к строке поиска (float:right).
nav .search-box button
Меняем цвет кнопки при наведении.
nav .search-box button:hover
До ширины экрана 625 пикселей панель навигации выглядит хорошо.

После 625 пикселей конструкция ломается, необходимо делать медиа-запрос для маленьких устройств.

Медиа-запросы
Первым делом отменим обтекание везде, где оно было (float:none), это позволит всем элементам занять вертикальное положение, на ширине экрана меньше, чем 625 пикселей.
@media screen and (max-width: 625px)
nav a, nav input[type=text], nav .search-box button
nav input[type=text]
>

Добавить иконку на кнопку Отправить
1) Добавить ссылку между тегами head:
2) Вставить иконку между тегами button:

Мы сделали лишь внешнюю сторону формы поиска по сайту, поиск пока не рабочий, то есть без программной части.
Посмотреть код целиком можно на Codepen

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Она выглядит вот так:
Комментарии ( 1 ):
Спасибо тебе, добрый человек! Ради отзыва решил даже зарегистрироваться на сайте. Это единственный поиск, который корректно подошел к моему сайту. За что огромное спасибо!
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Поле поиска для сайта. Идеи для оформления

Поле поиска для сайта — один из важнейших элементов пользовательского интерфейса на веб-странице. С его помощью пользователь может найти нужный контент на вашем сайте.
В этом уроке вы узнаете, как создать разметку для поля поиска с помощью HTML5, а также как стилизовать элементы формы, используя возможности CSS3, без использования скриптов.
1. Разметка HTML
Элемент является контейнером для формы поиска, поле поиска создается при помощи элемента или , а кнопка отправки данных на сервер может создаваться с помощью элемента или .

Чем отличается от ? Оба этих поля создают однострочное текстовое поле для ввода текста, но type=»search» добавлено в стандарт HTML5 и является семантической подсказкой для браузеров. Все браузеры, кроме Mozilla Firefox, добавляют крестик очистки в поле. Чтобы его убрать, можно поменять тип поля на type=»text» .
Чем отличается от ? Разницы в действии кнопок отправки, созданных первым или вторым способом, нет. Отличие состоит в том, что элемент является контейнером, следовательно внутрь него можно помещать другие элементы, например, изображения или иконки.
Текст в поля формы можно добавлять двумя способами:
1)
Цвет отображаемого текста будет серого цвета. С помощью следующих правил можно задать тексту-подсказке любой цвет, поменять начертание и фон поля. Эти селекторы нельзя совмещать в одно правило, иначе они не будут работать.
2)
Цвет отображаемого текста будет черного цвета. Задать свой цвет можно при помощи свойства color , например:
Похожие публикации:
- Как в wix использовать код css
- Как включить наушники xiaomi mi true wireless earbuds basic 2
- Как сделать увеличение картинки при наведении мыши css
- Как сделать фон сайта css
