Textarea in form css

HTML Tag

The tag defines a multi-line text input control.

The element is often used in a form, to collect user inputs like comments or reviews.

A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).

The size of a text area is specified by the cols and rows attributes (or with CSS).

The name attribute is needed to reference the form data after the form is submitted (if you omit the name attribute, no data from the text area will be submitted).

The id attribute is needed to associate the text area with a label.

Browser Support

Attributes

Attribute Value Description
autofocus autofocus Specifies that a text area should automatically get focus when the page loads
cols number Specifies the visible width of a text area
dirname textareaname.dir Specifies that the text direction of the textarea will be submitted
disabled disabled Specifies that a text area should be disabled
form form_id Specifies which form the text area belongs to
maxlength number Specifies the maximum number of characters allowed in the text area
name text Specifies a name for a text area
placeholder text Specifies a short hint that describes the expected value of a text area
readonly readonly Specifies that a text area should be read-only
required required Specifies that a text area is required/must be filled out
rows number Specifies the visible number of lines in a text area
wrap hard
soft
Specifies how the text in a text area is to be wrapped when submitted in a form

Global Attributes

Event Attributes

More Examples

Example

Disable default resize option:

Источник

Textarea in form css

Поле многострочного ввода в формах.

Обновлено 8 сентября 2022

Кратко

Скопировать ссылку «Кратко» Скопировано

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

Пример

Скопировать ссылку «Пример» Скопировано

  label for="story">Расскажите о себе:label> textarea id="story" name="story" rows="5" cols="33">Frontend-разработчик со стажемtextarea>      

Как понять

Скопировать ссылку «Как понять» Скопировано

На сайтах часто встречаются формы, где нужно писать многострочный текст. Например, когда нужно оставить комментарий, написать отзыв или статью. Для этих целей используется многострочное поле ввода, которое верстается тегом . Нужно отметить, что в этом поле можно писать только чистый текст. Панели стилизации текста, как в Ворде, являются дополнительными надстройками с использованием JavaScript.

Атрибуты

Скопировать ссылку «Атрибуты» Скопировано

autocomplete

Скопировать ссылку «autocomplete» Скопировано

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

on — поле будет автоматически заполняться значением, сохранённым в браузере во время предыдущей отправки формы

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

Если атрибут не указать совсем, то браузер будет брать значение из атрибута autocomplete родительского элемента , либо — если родительской формы нет — из той формы, на id которой ссылается атрибуте form .

 textarea autocomplete="off">textarea>      

autofocus

Скопировать ссылку «autofocus» Скопировано

Атрибут булевого типа (без значения, либо атрибут есть в теге, либо его нет совсем). Если он указан, то при загрузке страницы фокус будет автоматически помещён в данное поле ввода.

 textarea autofocus>textarea>      

cols

Скопировать ссылку «cols» Скопировано

Задаёт ширину поля ввода в символах. Если атрибут задан, то должен иметь значением целое положительное число. Если не задан, то по умолчанию берётся как 20

disabled

Скопировать ссылку «disabled» Скопировано

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

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

form

Скопировать ссылку «form» Скопировано

Атрибут указывает на элемент , с которым связано поле ввода. Значением атрибута должен быть id формы в пределах текущего документа. Если атрибут не задан, то обязательно должен находиться внутри тега form> . Но если задать атрибут, то нахождение внутри формы не обязательно и может находиться в любом месте страницы.

maxlength

Скопировать ссылку «maxlength» Скопировано

Максимальное число символов в поле (включая пробелы и переводы строк), которое может вводить пользователь. Значением должно быть положительное целое число

minlength

Скопировать ссылку «minlength» Скопировано

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

name

Скопировать ссылку «name» Скопировано

Имя поля. При отправке формы значение атрибута name будет ключом в отправляемом объекте

placeholder

Скопировать ссылку «placeholder» Скопировано

Подсказка для пользователя, что вводить в этом поле. Если подсказка должна быть многострочной, то можно прямо в HTML-коде переносить строки

Плейсхолдер должен давать только подсказку о том, как надо заполнять поле. Но это не полноценная замена тегу . Если на макете у полей ввода есть только плейсхолдер, но нет лейблов, то поговорите с дизайнером 😉

readonly

Скопировать ссылку «readonly» Скопировано

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

required

Скопировать ссылку «required» Скопировано

Атрибут булевого типа. Указывает, должно ли поле обязательно быть заполнено. Атрибут учитывается при валидации формы при отправке. Если поле не заполнить, то при попытке отправки формы браузер покажет ошибку

rows

Скопировать ссылку «rows» Скопировано

Задаёт высоту поля ввода в строках. Если атрибут задан, то должен иметь значением целое положительное число. Если не задан, то по умолчанию высота задаётся равной двум строкам.

spellcheck

Скопировать ссылку «spellcheck» Скопировано

Атрибут указывает, должна ли быть включена проверка правописания в поле. Может принимать следующие значения:

true — проверка правописания включена

default — указывает на поведение по умолчанию. При этом значении поле ввода может наследовать значение аналогичного атрибута от родительских элементов.

false — проверка правописания выключена

wrap

Скопировать ссылку «wrap» Скопировано

Атрибут определяет, будут ли добавлены символы переноса строк текста при отправке формы. Может принимать значения:

hard — когда форма отправляется, то браузер, основываясь на значении атрибута cols добавляет в текст служебные символы переноса строки (CR+LF). Таким образом, сохраняется информация о переносах строк, сделанных пользователем в поле ввода.

soft — значение по умолчанию. При отправке формы символы переноса строк добавлены не будут, и текст будет отправлен одной длинной строкой

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 По умолчанию поле ввода может изменять свой размер, если потянуть за нижний правый угол. Это поведение можно изменить, управляя CSS-свойством resize .

Источник

HTML Tag

The tag defines a form field where user can input a multi-line text. Unlike the tag, text wrapping inside is allowed when the form is submitted.

A text area can have an unlimited number of characters. The text within this tag is rendered in a fixed-width font (usually Courier).

Syntax

The ) tags.

Example of the HTML tag:

html> html> head> title>Title of the document title> head> body> form action="/form/submit" action="post"> textarea name="comment" rows="12" cols="35">Send your comments to the author. textarea>br> input type="submit" name="submitInfo" value="Submit"> form> body> html>

Result

textarea example

In this example we use the to define the text field, the name attribute to assign a name to this field (“comment”), the rows attribute to set its height (12 symbols) and the cols attribute to set its width (35 symbols).

Styling the element with CSS

The tag is considered to be a replaced element, as it has some intrinsic dimensions. Styling this tag is relatively easy with regular CSS.

Its valid and invalid values can be highlighted with the :valid and :invalid pseudo-classes. Valid and invalid values of a element can be highlighted using the :valid and :invalid pseudo-classes.

In most browsers,

Example of the HTML tag with CSS properties:

html> html> head> title>Title of the document title> style> .comment < width: 60%; height: 100px; padding: 10px; outline: 0; border: 3px solid #1c87c9; background: #d0e2bc; line-height: 20px; > style> head> body> form> p>Here we use CSS styles to customize the look of the text field. p> textarea class="comment"> Send your comments to the author. textarea> br> input type="submit" name="submitInfo" value="Submit"> form> body> html>

In this example we use CSS styles to customize the look of the text field.

Attributes

Attribute Value Description
autocomplete on
off
Specifies whether or not a text field should have autocomplete enabled.
autofocus autofocus Defines that a text area should automatically get focus when the page loads.
cols number Defines the visible width of a text area. Default value is 20 symbols.
dirname textareaname.dir Defines the text direction of the textarea when submitted.
disabled disabled Defines that a text area should be disabled.
form form_id Defines one or more forms the text area belongs to (via id).
maxlenght number Defines the maximum number of characters allowed in the text area.
minlength number Defines the minimum number of characters allowed in the text area.
name text Defines a name for a text area.
placeholder text Defines a short hint that describes the expected value of a text area. The hint is shown when the field is empty, and disappears when it gets focus.
readonly readonly Defines that a text area is read-only.
required required Defines that a text area must be filled out before the form is sent.
rows number Defines a visible number of rows in a text area. Default value is 2.
spellcheck true
false
default
Specifies whether the text in the tag should be spell checked by the underlying browser/OS.
wrap Defines how the text in a text area is to be wrapped when the form is submitted.
soft -(default value) the text is sent without any additional line breaks inserted.
hard -the browser automatically inserts line breaks so that each line has no more than the width of the control; for this to take effect the cols attribute must be specified.

How to style tag?

Common properties to alter the visual weight/emphasis/size of text in tag:

  • CSS font-style property sets the style of the font. normal | italic | oblique | initial | inherit.
  • CSS font-family property specifies a prioritized list of one or more font family names and/or generic family names for the selected element.
  • CSS font-size property sets the size of the font.
  • CSS font-weight property defines whether the font should be bold or thick.
  • CSS text-transform property controls text case and capitalization.
  • CSS text-decoration property specifies the decoration added to text, and is a shorthand property for text-decoration-line, text-decoration-color, text-decoration-style.

Coloring text in tag:

  • CSS color property describes the color of the text content and text decorations.
  • CSS background-color property sets the background color of an element.

Text layout styles for tag:

  • CSS text-indent property specifies the indentation of the first line in a text block.
  • CSS text-overflow property specifies how overflowed content that is not displayed should be signalled to the user.
  • CSS white-space property specifies how white-space inside an element is handled.
  • CSS word-break property specifies where the lines should be broken.

Other properties worth looking at for tag:

  • CSS text-shadow property adds shadow to text.
  • CSS text-align-last property sets the alignment of the last line of the text.
  • CSS line-height property specifies the height of a line.
  • CSS letter-spacing property defines the spaces between letters/characters in a text.
  • CSS word-spacing property sets the spacing between words.

Источник

Читайте также:  bootstrap split screen
Оцените статью