- HTML attribute: minlength
- Try it
- Examples
- Specifications
- Browser compatibility
- html.elements.input.minlength
- html.elements.textarea.minlength
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Html set text length
- # How to set Max Character length in CSS
- # Setting the max-width property to N pixels
- # How to set a Max Character length in CSS using grid
- # Additional Resources
- Атрибуты minlength и maxlength
- Кратко
- Как пишется
- Пример
- Как понять
HTML attribute: minlength
The minlength attribute defines the minimum string length that the user can enter into an or . The attribute must have an integer value of 0 or higher.
The length is measured in UTF-16 code units, which (for most scripts) is equivalent to the number of characters. If no minlength is specified, or an invalid value is specified, the input has no minimum length. This value must be less than or equal to the value of maxlength, otherwise the value will never be valid, as it is impossible to meet both criteria.
The input will fail constraint validation if the length of the text value of the field is less than minlength UTF-16 code units long, with validityState.tooShort returning true . Constraint validation is only applied when the value is changed by the user. Once submission fails, some browsers will display an error message indicating the minimum length required and the current length.
Try it
Examples
By adding minlength=»5″ , the value must either be empty or five characters or longer to be valid.
label for="fruit">Enter a fruit name that is at least 5 letters longlabel> input type="text" minlength="5" id="fruit" />
We can use pseudoclasses to style the element based on whether the value is valid. The value will be valid as long as it is either null (empty) or five or more characters long. Lime is invalid, lemon is valid.
input border: 2px solid currentcolor; > input:invalid border: 2px dashed red; > input:invalid:focus background-image: linear-gradient(pink, lightgreen); >
Specifications
Browser compatibility
html.elements.input.minlength
BCD tables only load in the browser
html.elements.textarea.minlength
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 30, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Html set text length
Last updated: Apr 28, 2023
Reading time · 4 min
# How to set Max Character length in CSS
To set max character length in CSS:
- Set the max-width CSS property on the element to N ch .
- Set the overflow CSS property to hidden .
- Optionally set text-overflow to ellipsis to display an ellipsis.
- Set white-space to nowrap to collapse the whitespace and suppress line breaks.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> p max-width: 15ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; > style> head> body> p>bobbyhadz.comp> p>This is a very long sentence.p> body> html>
The example sets the maximum character length of the p element to ~15 characters.
The ch relative unit represents the advance measure of the glyph 0 in the element’s font.
Copied!style> p max-width: 15ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; > style>
If it is impossible to determine the measure of the 0 glyph, it is assumed to be 0.5em wide by 1em tall.
We also set the overflow property to hidden .
When overflow is set to hidden , the overflowing content is clipped at the element’s padding box and the clipped content is not visible.
The text-overflow property can be set to ellipsis to display an ellipsis . that represents the clipped text.
If you don’t want to display an ellipsis, remove the property.
Copied!style> p max-width: 15ch; overflow: hidden; white-space: nowrap; > style>
When the white-space CSS property is set to nowrap :
# Setting the max-width property to N pixels
You can also set the max-width of the element to N pixels to truncate the text.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> p max-width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; > style> head> body> p>bobbyhadz.comp> p>This is a very long sentence.p> body> html>
The example sets the max-width CSS property on all p elements to 100px .
Note that the width of the ellipsis is also included in the 100px .
If you want to remove the ellipsis, you can remove the text-overflow property, however, that wouldn’t look good because a letter might be cut off.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> body margin: 100px; > p max-width: 100px; overflow: hidden; white-space: nowrap; > style> head> body> p>bobbyhadz.comp> p>This is a very long sentence.p> body> html>
# How to set a Max Character length in CSS using grid
You can also use CSS grid to set a max character length in CSS.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> .container display: grid; grid-template-columns: 1fr 15ch 1fr; > .paragraph grid-column: 2/3; > style> head> body> div class="container"> p class="paragraph">bobby hadz com abc 123 xyz.p> p class="paragraph">This is a very long sentence.p> div> body> html>
We wrap the p tags in a div and set the element’s display property to grid.
The grid value enables us to align elements into columns and rows.
The grid-template-columns CSS property can be used to define the track sizing of the grid columns.
In this case, we have 3 columns where the middle column has a maximum width of 15 characters.
We then set the grid-column CSS property on the p elements.
The property specifies the grid item’s size and location within a grid column.
A similar solution would be to simply set the max-width CSS property on the p elements to N characters.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> .paragraph max-width: 10ch; > style> head> body> p class="paragraph">bobby hadz com abc 123 xyz.p> p class="paragraph">This is a very long sentence.p> body> html>
N characters are displayed and then the text is wrapped to the next line.
You can also set the overflow-wrap property to anywhere to achieve a similar result.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> .paragraph max-width: 100px; word-break: normal; overflow-wrap: anywhere; > style> head> body> p class="paragraph">bobby hadz com abc 123 xyz.p> p class="paragraph">This is a very long sentence.p> body> html>
When the word-break CSS property is set to normal , the default line break rule is used.
When overflow-wrap is set to anywhere , unbreakable string of characters like long words or a URL may be broken at any point if there are no acceptable break points in the line.
Notice that the characters are still broken up nicely.
There is also a break-all value of the word-break property.
The break-all value inserts word breaks between any two characters to prevent overflow.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> .paragraph max-width: 100px; word-break: break-all; > style> head> body> p class="paragraph">bobby hadz com abc 123 xyz.p> p class="paragraph">This is a very long sentence.p> body> html>
However, notice that this makes the text a bit difficult to read.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- How to adjust a Button’s width to fit the Text in CSS
- Change Select Option Background-Color on Hover in CSS/HTML
- Check if Element is Input or Select dropdown in JavaScript
- Change a Button’s color onClick using JavaScript
- Change button text on Click using JavaScript
- How to Change Text color on Mouseover in JavaScript
- Add a class to the Clicked Element using JavaScript
- Check if Element was Clicked using JavaScript
- Hide element when clicked outside using JavaScript
- Set min-margin, max-margin, min-padding & max-padding in CSS
- How to Apply a CSS Hover effect to multiple Elements
- Changing Bold Text into Normal (Unbold Text) in HTML
- How to bring an element to the Front using CSS
- Apply multiple inline CSS styles to an HTML element
- Force the text in a Div to stay in one Line in HTML & CSS
- CSS text-align: center; not working issue [Solved]
- Tailwind CSS classes not working in Vanilla or React project
- Remove whitespace between inline-block elements using CSS
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Атрибуты minlength и maxlength
Атрибуты minlength и maxlength устанавливают полям ввода минимальное и максимальное количество символов.
Время чтения: меньше 5 мин
Это незавершённая статья. Вы можете помочь её закончить! Почитайте о том, как контрибьютить в Доку.
Кратко
Скопировать ссылку «Кратко» Скопировано
Атрибуты minlength и maxlength позволяют устанавливать минимальное и максимальное количество символов в полях ввода или .
Как пишется
Скопировать ссылку «Как пишется» Скопировано
input minlength="4" maxlength="8"> textarea minlength="50" maxlength="1000">
Пример
Скопировать ссылку "Пример" Скопировано
Создадим поле для ввода пароля и ограничим количество допустимых символов:
type="password" name="password" required minlength="8" maxlength="16">
label for="password">Введите пароль (от 8 до 16 символов):label> input type="password" id="password" name="password" required minlength="8" maxlength="16" >
Как понять
Скопировать ссылку "Как понять" Скопировано
Атрибуты minlength и maxlength устанавливают минимальное и максимальное количество символов в полях ввода или . Значением атрибутов должно быть целое число от 0 и выше. Если значение атрибутов не указано, или указано неправильно, ограничений по длине у поля не будет.
При добавлении полю обоих атрибутов, значение minlength всегда должно быть меньше значения maxlength . Если за этим не уследить, то поле всегда будет невалидным.