How do I limit the amount of characters in a textarea and input using CSS

Asked

Viewed 8,380 times

2

Good afternoon. I’m doing an activity in college where I need to limit a text field to 100 characters, but I have to use only CSS for this.

I’ve tried these two ways:

Example 1:

.es1[type="text"]{
    background-color: rgb(173,234,234);
    font-weight: bolder;
    width: 20ch;

Example 2:

.es1[type="text"]{
    background-color: rgb(173,234,234);
    font-weight: bolder;
    max-width: 20ch;

But I couldn’t. I thank you ;)

  • With CSS??? You’ll never get that. You probably missed some of the activity.

  • The attribute is commonly used input[maxlength] or textarea[maxlength]. But CSS I’ve never seen.

  • if used max-width: 15ch; and overflow: hidden;, you can delimit the number of lines for certain tags, such as <p>, but not a value input field

2 answers

4

If you want to limit the number of characters inside the input you can use maxlength="100" and to fit inside it visually exactly 100 characters you can put width: 100ch

In this example you can see, I have limited to 10 characters only as well as the width in 10ch only 10 characters wide on the input. But read the remark below.

.es1[type="text"]{
  width: 10ch; /* largura equivalente a 10 letras (10ch) */
  background-color: rgb(173,234,234);
  font-weight: bolder;
}
<!-- o campo só deixa digitar 10 caracteres como o maxlength -->
<input class="es1" type="text" value="1234567890" maxlength="10">
<input class="es1" type="text" value="mmmmm" maxlength="10">

OBS:

According to Mozilla documentation https://developer.mozilla.org/en-US/docs/Web/CSS/length

CH Represents the width, or more precisely the advanced measure, of glyph "0" (zero, the Unicode character U + 0030) in the element.

Rezumindo, if you fill in 10 characters 0 It’ll be fine, but if it’s 10 letters M will not fit in the width of the input

Support from browsers to unit CH: https://caniuse.com/#feat=ch-Unit

2

I always use direct in HTML maxlength.

Get like this, and you can wear so much on input how much in the textarea:

<textarea name="mensagem" rows="7" maxlength="512" ></textarea>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.