Ширина текстового поля

Зафиксировать размеры поля ввода текста

Красным обведена область, при нажатии на которую и перемещении поле ввода текста вытягивается за пределы шаблона и портит весь вид(.. Есть ли какие-либо фиксы для того, чтобы это поле оставалось фиксированным ине растягивалось..

Очистка поля ввода текста
Ребят, добрый день. Вопрос следующий : есть функция "очистки поля" и 2 поля ввода. function.

Создание поля ввода текста
Не получается создать поле ввода текста с последующей публикацией его на странице (как в гостевой).

Форматирование текста внутри поля текстового ввода
Столкнулся с проблемой: необходимо на лету редактировать текст внутри поля текстового ввода. .

textarea placeholder=" Скажите что-нибудь остальным.." name="short_story" id="short_story" onclick=setFieldName(this.name) style="width:100%;height:25" rows="5" class="f_textarea" cols="10" >/textarea>

Эксперт HTML/CSS

При резиновой вёрстке не получится. Либо задавайте для ширины и высоты фиксированные размеры. В любом случае по высоте, если не будет фиксированного размера блока он будет тянутся до посинения. По ширине можно ограничить(max-width)задать например не 100%, а 80%. И то насколько я помню — это не кроссбраузерный вариант. А так whiteapps Вам уже дал ответ. И ещё у Вас ошибка в коде не задана размерность высоты.

Как зафиксировать размеры блока при масштабировании в браузере?
Скажите пожалуйста мне нужно чтобы в правом угле была стрелка(картинкой) но когда я колёсиком мыши.

value поля ввода текста
как мне через функцию передать значение текстового поля с name=1_1 в поле name=2_1 при нажатии.

Читайте также:  Execute javascript with python

Расширение поля ввода текста
Здравствуйте! На форме у меня есть текстбокс, иногда приходится вводить длинные строки а места на.

Как зафиксировать размеры столбцов DGV
Здравствуйте! Есть Datagridview. В нем 4 колонки с такими параметрами: .

Отслеживание ввода текста в текстовые поля
Всем доброго времени суток! Не могу решить проблемку ввиду того, что не могу правильно.

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

Источник

Как установить ширину текстового поля в пикселах?

Задать ширину текстового поля в пикселах через стили.

Решение

Ширина текстового поля, создаваемого с помощью тега , определяется стилевым свойством width , значение которого можно устанавливать в пикселах, процентах или других допустимых единицах, как показано в примере 1.

HTML5 CSS 2.1 IE Cr Op Sa Fx

        

Введите ваше имя:

Результат данного примера показан ниже.

Рис. 1

Рис. 1. Текстовое поле с фиксированной шириной

В данном примере задана ширина поля в пикселах путем добавления свойства width к идентификатору поля user .

Заметьте, что ширина поля также определена с помощью атрибута size тега , но в случае применения стилей этот параметр игнорируется.

HTML по теме

CSS по теме

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Популярные рецепты

  • Как добавить картинку на веб-страницу?
  • Как добавить иконку сайта в адресную строку браузера?
  • Как добавить фоновый рисунок на веб-страницу?
  • Как сделать обтекание картинки текстом?
  • Как растянуть фон на всю ширину окна?
  • Как выровнять фотографию по центру веб-страницы?
  • Как разместить элементы списка горизонтально?
  • Как убрать подчеркивание у ссылок?
  • Как убрать маркеры в маркированном списке?
  • Как изменить расстояние между строками текста?
  • Как сделать, чтобы картинка менялась при наведении на нее курсора мыши?
  • Как открыть ссылку в новом окне?

Источник

Зафиксировать размеры поля ввода текста

Красным обведена область, при нажатии на которую и перемещении поле ввода текста вытягивается за пределы шаблона и портит весь вид(.. Есть ли какие-либо фиксы для того, чтобы это поле оставалось фиксированным ине растягивалось..

Очистка поля ввода текста
Ребят, добрый день. Вопрос следующий : есть функция "очистки поля" и 2 поля ввода. function.

Создание поля ввода текста
Не получается создать поле ввода текста с последующей публикацией его на странице (как в гостевой).

Форматирование текста внутри поля текстового ввода
Столкнулся с проблемой: необходимо на лету редактировать текст внутри поля текстового ввода. .

textarea placeholder=" Скажите что-нибудь остальным.." name="short_story" id="short_story" onclick=setFieldName(this.name) style="width:100%;height:25" rows="5" class="f_textarea" cols="10" >/textarea>

Эксперт HTML/CSS

При резиновой вёрстке не получится. Либо задавайте для ширины и высоты фиксированные размеры. В любом случае по высоте, если не будет фиксированного размера блока он будет тянутся до посинения. По ширине можно ограничить(max-width)задать например не 100%, а 80%. И то насколько я помню — это не кроссбраузерный вариант. А так whiteapps Вам уже дал ответ. И ещё у Вас ошибка в коде не задана размерность высоты.

Как зафиксировать размеры блока при масштабировании в браузере?
Скажите пожалуйста мне нужно чтобы в правом угле была стрелка(картинкой) но когда я колёсиком мыши.

value поля ввода текста
как мне через функцию передать значение текстового поля с name=1_1 в поле name=2_1 при нажатии.

Расширение поля ввода текста
Здравствуйте! На форме у меня есть текстбокс, иногда приходится вводить длинные строки а места на.

Как зафиксировать размеры столбцов DGV
Здравствуйте! Есть Datagridview. В нем 4 колонки с такими параметрами: .

Отслеживание ввода текста в текстовые поля
Всем доброго времени суток! Не могу решить проблемку ввиду того, что не могу правильно.

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

Источник

How to stretch input field to full width?

I have a simple HTML form. I’d like the right widgets in the second column (text field, combox, and so on) to stretch and fill the full column. My HTML looks like this:

 
Report Number
Report Type
.formTable < border-color: black; >.formTable td < padding: 10px; >.formTable .col1 < text-align: right; >.formTable .col2

5 Answers 5

You can specify that all of the children of class «col2» have a width of 100% by adding the following:

Start with semantic markup since this isn’t tabular data. Also, with added labels, we don’t need extra wrapper DIVs, which is cleaner.

.formList < border:1px solid #000; padding:10px; margin:10px; >label < width:200px; margin-left:-200px; float:left; >input, select < width:100%; >li

In this WhatWG spec (whatwg.org/specs/web-apps/current-work/multipage/…) it says: The table element represents data with more than one dimension, in the form of a table. key/value pairs are two dimensional, so table is ok for me.

On that same page it says «Tables must not be used as layout aids.» Wouldn’t using tables to align a label next to an input constitute as controlling page layout instead of properly semantic code?

I think layout is meant as ‘page layout’ which means the layout of the whole page and not just laying out data in a section of the page.

This works nicely except for one thing: you lose the vertical baseline alignment between label and input. Any solution that works along these lines, but also preserves that baseline alignment?

To match any .col2 descendant. as you can see here. Or:

To match just the immediate children.

if using Twitter Bootstrap: and input is inside a column

just add to the class=»container-fluid»

No way to tell from a code snippet if bootstrap is being used or not. If there was a bootstrap tag, it is no longer required. This might answer the question, per stated condition. And it was helpful for me.

Note

This is not an answer, but a comment, which includes too much code to go into the comment section. So please refrain from downvoting me, would you? 🙂

Other semantic markup additionaly to Matthew Darnells answer:

If you wrap the labels around the inputs and selects, you can avoid using the for and id attributes.

Or use a definition list which might give you additional control

 

Источник

width:auto for fields

An ‘s width is generated from its size attribute. The default size is what’s driving the auto width.

You could try width:100% as illustrated in my example below.

Smaller size, smaller width:

Here’s the best I could do after a few minutes. It’s 1px off in FF, Chrome, and Safari, and perfect in IE. (The problem is #^&* IE applies borders differently than everyone else so it’s not consistent.)

Thanks. width:100% is not the same thing tho. It will overflow the parent box if there are margins or a border.

You could explicitly set these to adjust how you want, e.g. border:2px inset #eee; margin:-2px . Haven’t tested it myself though but something along those lines.

Thanks Steve. You should also check out stackoverflow.com/questions/1030793/… which has some other interesting ideas.

you can use set the inputs box-sizing property to border-box to stop the border from overlapping the container.

ORIGINAL answer using Angular: Because input ‘s width is controlled by it’s size attribute, this is how I initialize an input width according to its content:

UPDATE for JavaScript (10/01/2022): My original answer was from the time I was studying Angular. If you need pure, Vanilla JavaScript the solution is even simpler:

Or add an «input» event listener to your input html element and run a code like this:

const myInput = document.querySelector('input'); myInput.addEventListener('input', this.typing); 

Obs: Depending on the browser, input may restore to its default size of something between 150px and 250px if/when size gets the 0 value. In this case, just add +1 to value.length :

Although this #angular specific answer is not a valid answer to the OP’s question (and I’m not upvoting), I did come to this topic just to find this particular idea.

Watch out since [size]=»0″ will give an error. And with any solution setting size you may want to use font-family: monospace since . is a lot narrower than WWWWW and size does not consider the contents, just the length at the current font size.

Note that the size attribute is only valid for email , password , tel , and text input types. developer.mozilla.org/en-US/docs/Web/HTML/Element/…. Other input types must be controlled with CSS width (developer.mozilla.org/en-US/docs/Web/HTML/Element/input/…).

«Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section.»

No one actually answered the above part of the original poster’s question.

As long as the value of width is auto, the element can have horizontal margin, padding and border without becoming wider than its container.

On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border. This may be what you want, but most likely it isn’t.

To visualise the difference I made an example: http://www.456bereastreet.com/lab/width-auto/

As stated in the other answer, width: auto doesn’t work due to the width being generated by the input’s size attribute, which cannot be set to «auto» or anything similar.

There are a few workarounds you can use to cause it to play nicely with the box model, but nothing fantastic as far as I know.

First you can set the padding in the field using percentages, making sure that the width adds up to 100%, e.g.:

Another thing you might try is using absolute positioning, with left and right set to 0. Using this markup:

This absolute positioning will cause the input to fill the parent fieldset horizontally, regardless of the input’s padding or margin. However a huge downside of this is that you now have to deal with the height of the fieldset, which will be 0 unless you set it. If your inputs are all the same height this will work for you, simply set the fieldset’s height to whatever the input’s height should be.

Other than this there are some JS solutions, but I don’t like applying basic styling with JS.

It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div — then set your input to 100%.

If you’re willing to include a little JavaScript to solve this, you can get exact sizing. This doesn’t rely on approximating width with size or em s, doesn’t rely on any hardcoded element widths, and works for e.g., type=»number» , which don’t accept a size attribute.

The trick is to get your input sized exactly like a span with the same content, by actually having an invisible span with the same content.

Put your input inside a div along with a span that mirrors the input ‘s value. Give both the input and the span the same styling, give the input 100% width , then hide the span and absolute-position the input to sit on top of the span .

This way, the container (and thus the input ) are automatically sized by the visual appearance of the content of the invisible span .

codepen screenshot

 

Источник

Оцените статью