Что такое длина Input, как изменить размер текстового поля
Важнейшим атрибутом у тега «input» является «type». Именно он определяет какое поле будет перед нами: текстовое, для пароля, чекбокс, радио и др. Поэтому, чтобы определить тег «input», как текстовое поле нужно воспользоваться вот таким синтаксисом:
Обозначив тег «input» таким образом мы получим текстовое поле в форме, но оно будет с «гибким» размером. То есть, оно растянется на всю ширину контейнера, в котором мы обозначили тег «input». Такой подход не всегда уместен. Иногда нам нужно чтобы текстовое поле было определенного размера. Мы можем это сделать, если задействовать CSS-свойство «width» для конкретного поля «input» или прямо внутри самого тега мы можем задействовать свойство «size». В свойстве «size» нужно прописать какое-то число, где число будет определять ширину поля, а обозначать количество видимых символов.
Кстати, когда говорят «длина input» – это немного не корректное высказывание, потому что правильнее будет говорить «ширина input» или «размер input».
Как выставляется ширина(длина, размер) «input» в HTML на примере
Давайте сверстаем небольшую HTML-форму, где у нас будет текстовое поле «input» заданной ширины. Код будет вот таким:
#userForm
width: 600px; /*Определяем пиксельную ширину текстового поля с помощью CSS-свойств */
>
Введите ваше имя:
Результат этой формы можно увидеть на рисунке ниже:
Важно отметить, что размер текстового поля «input» в CSS-свойствах можно определить разными единицами измерения: в пикселях, процентах и других измерительных единицах. А в свойстве «size» можно указать только количество видимых текстовых символов в виде числа. На примере, что мы привели выше, мы указали оба варианта определения размера поля «input». На практике так делать не надо, потому что в этом случае сработает только CSS-свойство, так как оно по иерархии главнее, чем внутреннее свойство «size».
Заключение
Сегодня мы рассказали, что длина, ширина и размер текстового поля «input» в HTML – это определения одного и того же свойства и правильно его называть «ширина input». На примере мы показали, что установить размер текстового поля всегда можно при помощи CSS-свойства «width», либо использовать внутреннее свойства текстового поля «input» – «size».
Мы будем очень благодарны
если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.
How can the size of an input text box be defined in HTML?
and in a separate CSS file apply the necessary styling:
If you want to limit the number of characters that the user can type into this textbox you could use the maxlength attribute:
also: you can change the width in terms of «em» (and not «px») and then the size is proportional to the font-size of the text box
The size attribute works, as well
If the input is type «text» or «password» then the size refers to the number of characters. You can control the width of the input that way. See Mozilla docs
Well- The font-size (style=»font-size:18pt») was the one I was looking for and that also increases the size of the box. Though not explicitly asked by the OP, it also adds value.
This worked. Hence thanks a lot. However the text seems to center itself vertically. Can I prevent this in any way?
You can set the width in pixels via inline styling:
You can also set the width with a visible character length:
The «size» specifies the visible width in characters of the element input.
You can also use the height and width from css.
Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Input size vs width
Which one is optimal cross-browser code? Of course it depends on requirements, but I’m curious to know how people decide and on what basis.
It’s usually a bad idea to use «px» on the web. You might consider using relative units instead («em», «%», etc.).
10 Answers 10
You can use both. The css style will override the size attribute in browsers that support CSS and make the field the correct width, and for those that don’t, it will fall back to the specified number of characters.
Edit: I should have mentioned that the size attribute isn’t a precise method of sizing: according to the HTML specification, it should refer to the number of characters of the current font the input will be able to display at once.
However, unless the font specified is a fixed-width/monospace font, this is not a guarantee that the specified number of characters will actually be visible; in most fonts, different characters will be different widths. This question has some good answers relating to this issue.
The snippet below demonstrates both approaches.
@font-face < font-family: 'Diplomata'; font-style: normal; font-weight: 400; src: local('Diplomata'), local('Diplomata-Regular'), url(https://fonts.gstatic.com/s/diplomata/v8/8UgOK_RUxkBbV-q561I6kFtXRa8TVwTICgirnJhmVJw.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215; >@font-face < font-family: 'Open Sans Condensed'; font-style: normal; font-weight: 300; src: local('Open Sans Condensed Light'), local('OpenSansCondensed-Light'), url(https://fonts.gstatic.com/s/opensanscondensed/v11/gk5FxslNkTTHtojXrkp-xBEur64QvLD-0IbiAdTUNXE.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215; >p < margin: 0 0 10px 0; >input < font-size: 20px; >.narrow-font < font-family: 'Open Sans Condensed', sans-serif; >.wide-font < font-family: 'Diplomata', cursive; >.set-width
Most fonts are not mono-width. Regarding «the number of characters the field will be able to display at once». Which character do you mean?
@jbyrd Yes, that is the case—but the answer is correct according to the HTML specification. I’ve edited the answer now to clarify things a bit.
I suggest, probably best way is to set style’s width in em unit 🙂 So for input size of 20 characters just set style=’width:20em’ 🙂
In CSS, em is relative to the font-size of its direct or nearest parent. An example: if the inherited font-size of an element is 16px, and you set the font-size to be 2em, the resulting size will be 32px (16px*2em). The «em» unit is not character quantity. More: w3.org/TR/css3-values/#font-relative-lengths and kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs and j.eremy.net/confused-about-rem-and-em
@Jess, good question. In typography, ’em’ used to mean the width of the ‘M’ character. For a long time, I believed the same thing. However, in CSS and digital typography, the ’em’ equals the height of the font in points. This is to accommodate character sets that do not have the ‘M’ character, or where the ‘M’ is not the full height or width of the font.
size is inconsistent across different browsers and their possible font settings.
The width style set in px will at least be consistent, modulo box-sizing issues. You might also want to set the style in ‘em’ if you want to size it relative to the font (though again, this will be inconsistent unless you set the input’s font family and size explicitly), or ‘%’ if you are making a liquid-layout form. Either way, a stylesheet is probably preferable to the inline style attribute.
You still need size for to get the height to line up with the options properly. But I’d not use it on an .
I want to say this goes against the «conventional wisdom», but I generally prefer to use size. The reason for this is precisely the reason that many people say not to: the width of the field will vary from browser to browser, depending on font size. Specifically, it will always be large enough to display the specified number of characters, regardless of browser settings.
For example, if I have a date field, I typically want the field wide enough to display either 8 or 10 characters (two digit month and day and either two or four digit year, with separators). Setting the size attribute essentially guarantees me that the entire date will be visible, with minimal wasted space. Similarly for most numbers — I know the range of values expected, so I’ll set the size attribute to the proper number of digits, plus decimal point if applicable.
As far as I can tell, no CSS attribute does this. Setting a width in em, for example, is based off the height, not the width, and thus is not very precise if you want to display a known number of characters.
Of course, this logic doesn’t always apply — a name entry field, for example, could contain any number of characters. In those cases I’ll fall back to CSS width properties, typically in px. However, I would say the majority of fields I make have some sort of known content, and by specifying the size attribute I can make sure that most of the content, in most cases, is displayed without clipping.