Sorry for this question but I can’t seem to find an answer anywhere.
I have CSS code that should set the height of my text box. I am using VS2010 Express for Windows phone, coding in HTML/CSS/Javascript/C#.
HTML
<input class="heighttext" type="text" id="name">
CSS
.heighttext{
height:30px
}
I can set the height to anything I like, but the text box will stay the same!
Please help, or at least send me a link that can!
Flip
5,9717 gold badges42 silver badges72 bronze badges
asked Oct 15, 2012 at 9:54
3
Try with padding and line-height —
input[type="text"]{ padding: 20px 10px; line-height: 28px; }
answered Oct 15, 2012 at 9:59
DipakDipak
11.8k1 gold badge29 silver badges31 bronze badges
4
Form controls are notoriously difficult to style cross-platform/browser. Some browsers will honor a CSS height rule, some won’t.
You can try line-height (may need display:block; or display:inline-block;) or top and bottom padding also. If none of those work, that’s pretty much it — use a graphic, position the input in the center and set border:none; so it looks like the form control is big but it actually isn’t…
answered Oct 15, 2012 at 10:01
danwellmandanwellman
8,9198 gold badges61 silver badges87 bronze badges
You should use font-size for controlling the height, it is widely supported amongst browsers.
And in order to add spacing, you should use padding.
Forexample,
.inputField{
font-size: 30px;
padding-top: 10px;
padding-bottom: 10px;
}
answered Apr 27, 2019 at 4:29
RustyRusty
3,8803 gold badges34 silver badges45 bronze badges
Don’t use height property in input field.
Example:
.heighttext{
display:inline-block;
padding:15px 10px;
line-height:140%;
}
Always use padding and line-height css property. Its work perfect for all mobile device and all browser.
answered Apr 27, 2019 at 4:40
HAPPY SINGHHAPPY SINGH
5264 silver badges13 bronze badges
The best way to do this is:
input.heighttext{
padding: 20px 10px;
line-height: 28px;
}
answered Mar 13, 2020 at 4:17
You use this style code
.heighttext{
float:right;
height:30px;
width:70px;
}
answered Oct 15, 2012 at 10:00
SaeedSaeed
3,0953 gold badges24 silver badges40 bronze badges
I would suggest learning to use a LESS or SASS compiler for your bootstrap files, and download the LESS/SASS files along with Bootstrap. It’s not very difficult and is really the way you are «supposed» to customize Bootstrap. It might be a little heavy-handed for one or two tweaks, but for things like the overall color scheme or grid / input control spacing and padding it really is much better as the LESS variables are universal and might apply to things that you wouldn’t think to override.
For example, you should be decorating all of your inputs with the «form-control» class. The «form-control» and «output» classes are defined in the file: forms.less, and the height of the field is based on many variables check it out:
.form-control {
display: block;
width: 100%;
height: @input-height-base; // Make inputs at least the height of their button counterpart (base line-height + padding + border)
padding: @padding-base-vertical @padding-base-horizontal;
font-size: @font-size-base;
line-height: @line-height-base;
color: @input-color;
background-color: @input-bg;
background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214
border: 1px solid @input-border;
border-radius: @input-border-radius; // Note: This has no effect on <select>s in some browsers, due to the limited stylability of <select>s in CSS.
.box-shadow(inset 0 1px 1px rgba(0,0,0,.075));
...more stuff I removed...
}
All of the variables are defined in a single, easy to work with file, and changes made there affect everything. Here’s a sample:
//== Components
//
//## Define common padding and border radius sizes and more. Values based on 14px text and 1.428 line-height (~20px to start).
@padding-base-vertical: 6px;
@padding-base-horizontal: 12px;
@padding-large-vertical: 10px;
@padding-large-horizontal: 16px;
@padding-small-vertical: 5px;
@padding-small-horizontal: 10px;
@padding-xs-vertical: 1px;
@padding-xs-horizontal: 5px;
@line-height-large: 1.3333333; // extra decimals for Win 8.1 Chrome
@line-height-small: 1.5;
@border-radius-base: 4px;
@border-radius-large: 6px;
@border-radius-small: 3px;
//** Global color for active items (e.g., navs or dropdowns).
@component-active-color: #fff;
//** Global background color for active items (e.g., navs or dropdowns).
@component-active-bg: @brand-primary;
//** Width of the `border` for generating carets that indicate dropdowns.
@caret-width-base: 4px;
//** Carets increase slightly in size for larger components.
@caret-width-large: 5px;
If a new version of BS comes out, you simply apply your old variables to the new BS files using the compiler.
Links:
http://getbootstrap.com/customize/
http://lesscss.org/
Visual studio users:
https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebCompiler
I would suggest learning to use a LESS or SASS compiler for your bootstrap files, and download the LESS/SASS files along with Bootstrap. It’s not very difficult and is really the way you are «supposed» to customize Bootstrap. It might be a little heavy-handed for one or two tweaks, but for things like the overall color scheme or grid / input control spacing and padding it really is much better as the LESS variables are universal and might apply to things that you wouldn’t think to override.
For example, you should be decorating all of your inputs with the «form-control» class. The «form-control» and «output» classes are defined in the file: forms.less, and the height of the field is based on many variables check it out:
.form-control {
display: block;
width: 100%;
height: @input-height-base; // Make inputs at least the height of their button counterpart (base line-height + padding + border)
padding: @padding-base-vertical @padding-base-horizontal;
font-size: @font-size-base;
line-height: @line-height-base;
color: @input-color;
background-color: @input-bg;
background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214
border: 1px solid @input-border;
border-radius: @input-border-radius; // Note: This has no effect on <select>s in some browsers, due to the limited stylability of <select>s in CSS.
.box-shadow(inset 0 1px 1px rgba(0,0,0,.075));
...more stuff I removed...
}
All of the variables are defined in a single, easy to work with file, and changes made there affect everything. Here’s a sample:
//== Components
//
//## Define common padding and border radius sizes and more. Values based on 14px text and 1.428 line-height (~20px to start).
@padding-base-vertical: 6px;
@padding-base-horizontal: 12px;
@padding-large-vertical: 10px;
@padding-large-horizontal: 16px;
@padding-small-vertical: 5px;
@padding-small-horizontal: 10px;
@padding-xs-vertical: 1px;
@padding-xs-horizontal: 5px;
@line-height-large: 1.3333333; // extra decimals for Win 8.1 Chrome
@line-height-small: 1.5;
@border-radius-base: 4px;
@border-radius-large: 6px;
@border-radius-small: 3px;
//** Global color for active items (e.g., navs or dropdowns).
@component-active-color: #fff;
//** Global background color for active items (e.g., navs or dropdowns).
@component-active-bg: @brand-primary;
//** Width of the `border` for generating carets that indicate dropdowns.
@caret-width-base: 4px;
//** Carets increase slightly in size for larger components.
@caret-width-large: 5px;
If a new version of BS comes out, you simply apply your old variables to the new BS files using the compiler.
Links:
http://getbootstrap.com/customize/
http://lesscss.org/
Visual studio users:
https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebCompiler
Рано или поздно вы получите от дизайнера макет, где встретится он — с виду вроде бы обычный текстовый инпут, а на деле, меняющий свою ширину или высоту, в зависимости от содержимого. Хорошие новости — отчаиваться не будем, это возможно. Причем, возможно достаточно разнообразными способами, об одном из них сегодня и поговорим.
Проблема
Прежде чем кидаться решать проблему — ее нужно осознать. С чего бы начать? Все зависит от поставленной вам задачи. Например: если требуется, чтобы инпут расширялся в ширину — это одна проблема. Если нужно чтобы он рос в высоту — это проблема другая. А если нужно чтобы сразу во все стороны, тут можно начинать страдать, дело-то непростое.
Главная проблема состоит в том, что элементы ввода не умеют растягиваться по своему содержимому. Это очень досадно и конечно мир был бы лучше, если бы они умели, но увы. Более того, однострочное текстовое поле — input вообще бессмысленно растягивать в высоту, содержимое все равно не ляжет в несколько строк, так уж он устроен. Поэтому дальше начинаются любимые фронтендерами лайфхаки.
Варианты решения
Самый первый, приходящий в топ выдачи гугла — это просто взять и заменить инпут на div с атрибутом contenteditable — и вот оно, проблема решена! Вот вам адаптивный по высоте/ширине див и редактируемое содержимое. Но если для вас (как и для меня) это не вариант, то смотрим дальше.
Следующий вариант не назовешь слишком изящным, но работающий вот что важно. Основан на том, что где-то позади самого текстового поля мы прячем невидимый блок, куда дублируем содержимое текстового поля при любом изменении. Блок изменяет свои размеры по содержимому, мы вычисляем их с помощью ява-скрипта и присваиваем текстовому полю. Если вас не смущает дополнительный мусор на странице в виде такого вот костыля — смело можно брать на вооружение.
Ну и третий вариант, который мне больше всего пришелся по душе — это все-таки вычислять содержимое текстового инпута и адаптировать его ширину/высоту, чтобы все помещалось. Давайте на него посмотрим чуть более внимательно.
Выбираем правильный инпут
Прежде всего, понадобится заменить input на textarea. Поскольку инпуты бесполезно наращивать в высоту, лучше сразу возьмем многострочное поле и будем делать вид, что это однострочный инпут.
Добавляем немного стилей, чтобы замаскировать истинную сущность нашего текстового поля.
.textarea {
font-size: 24px;
font-family: Arial;
border-radius: 8px;
resize: none;
padding: 5px;
overflow: hidden;
box-sizing: border-box;
height: 40px;
min-height: 40px;
width: 400px;
margin-bottom: 15px;
}
Тут следует обратить внимание на три обязательных параметра, без которых ничего не сработает: box-sizing, height, min-height.
box-sizing: border-box
В обязательном порядке box-sizing должен быть в значении border-box, чтобы когда вы добавите паддинг в текстовом поле, а вы его обязательно добавите, он не увеличивал дополнительно высоту или ширину текстового поля, а откладывался бы вовнутрь.
height и min-height (width и min-width)
Тут все просто: height — чтобы изначально textarea выглядела бы как input. min-height — чтобы при сбросе значения высоты текстовое поле не прыгало, а оставалось минимально необходимого размера. Все это справедливо и для свойств width и min-width.
Немного теории
Принцип действия очень простой. У каждого DOM-элемента, который может содержать контент, есть readonly-свойство scrollHeight (scrollWidth) которое и содержит так нужную нам, истинную высоту элемента, такую, при которой все содержимое этого элемента будет видно пользователю. Все, что нам требуется — при изменении текстового поля, вычислять значение scrollHeight/scrollWidth и присваивать его текстовому полю.
А для того, чтобы текстовое поле могло еще и возвращаться к своему исходному виду, перед изменением, будем сбрасывать установленную ранее высоту до нуля, для того чтобы свойство scrollHeight корректно бы показало нам, есть ли контент, не умещающийся в текстовом поле.
Немного vanilla JS-практики
Специально не использовала никаких фреймворков, для большей гибкости. Любым удобным способом получаем текстовое поле со страницы и добавляем обработчик события input
const textareaHeight = document.getElementById("text");
textareaHeight.addEventListener("input", (event) => {
textareaHeight.style.height = 0;
textareaHeight.style.height = textareaHeight.scrollHeight + "px";
})
Это ввод с клавиатуры. Не стоит забывать, что текстовые поля бывают заполняются автоматически, извне. Для этого добавляем отдельный метод вставки значения:
function setValue(text: string) {
const textarea = document.getElementById("text");
textarea.style.height = 0;
textarea.value = text;
textarea.style.height = textarea.scrollHeight + "px";
}
Ну и давайте для ширины тоже сделаем. Все то же самое, только тут уже берем input, и высоту меняем на ширину.
const textInput = document.getElementById("text");
textInput.addEventListener("input", (event) => {
textInput.style.width = 0;
textInput.style.width = textInput.scrollWidth + "px";
})
function setValue(text: string) {
const textInput = document.getElementById("text");
textInput.style.width = 0;
textInput.value = text;
textInput.style.width = textInput.scrollWidth + "px";
}
Результат
Вот такие поля получились. Несложно и недолго.
Адаптивный инпут, растущий в высоту:
See the Pen Adaptive Height Text Input with Vanilla JS by dreamhelg (@dreamhelg) on CodePen.dark
Адаптивный инпут, растущий в ширину:
See the Pen Adaptive Width Text Input with Vanilla JS by dreamhelg (@dreamhelg) on CodePen.dark
Angular Директива
Для тех, кто дочитал аж до сюда — бонус. Если лень самостоятельно упаковать все это в директиву, я уже все сделала за вас, смотрите:
@Directive({
selector: "[adaptiveInputDirective]"
})
export class AdaptiveInputDirective implements OnInit {
@Input() horizontal: boolean;
constructor(private element: ElementRef) {}
ngOnInit() {
if (this.horizontal) {
this.element.nativeElement.style.whiteSpace = "nowrap";
}
}
@HostListener("ngModelChange", ["$event"])
onChange(): void {
const input = this.element.nativeElement;
if (this.horizontal) {
input.style.width = 0;
input.style.width = input.scrollWidth + "px";
} else {
input.style.height = 0;
input.style.height = input.scrollHeight + "px";
}
}
}
Здесь используется уже знакомый вам декоратор @HostListener. А если еще не знакомый, то обязательно почитайте статью об этом.
Пример использования:
<textarea formcontrolname="myText" adaptiveinputdirective=""></textarea>
Да, можно обойтись одним элементом — textarea. Просто, если нужна адаптивность в ширину — добавим CSS-свойство white-space: nowrap — запрет на перенос строк.
В остальном, все, о чем говорили, плюс — настраиваемый параметр horizontal указывающий что тянуть, ширину или высоту. Выбирайте нужный вариант и ни в чем не отказывайте своему дизайнеру.
Посмотреть как работает на stackblitz.com
Приходилось вам сталкиваться с подобной задачей? Как решали?
