Css textarea вертикальное выравнивание

vertical-align

The vertical-align CSS property sets vertical alignment of an inline, inline-block or table-cell box.

Try it

The vertical-align property can be used in two contexts:

  • To vertically align an inline-level element’s box inside its containing line box. For example, it could be used to vertically position an image in a line of text.
  • To vertically align the content of a cell in a table.

Note that vertical-align only applies to inline, inline-block and table-cell elements: you can’t use it to vertically align block-level elements.

Syntax

/* Keyword values */ vertical-align: baseline; vertical-align: sub; vertical-align: super; vertical-align: text-top; vertical-align: text-bottom; vertical-align: middle; vertical-align: top; vertical-align: bottom; /* values */ vertical-align: 10em; vertical-align: 4px; /* values */ vertical-align: 20%; /* Global values */ vertical-align: inherit; vertical-align: initial; vertical-align: revert; vertical-align: revert-layer; vertical-align: unset; 

The vertical-align property is specified as one of the values listed below.

Values for inline elements

Parent-relative values

These values vertically align the element relative to its parent element:

Aligns the baseline of the element with the subscript-baseline of its parent.

Aligns the baseline of the element with the superscript-baseline of its parent.

Читайте также:  Java массив поиск элементов

Aligns the top of the element with the top of the parent element’s font.

Aligns the bottom of the element with the bottom of the parent element’s font.

Aligns the middle of the element with the baseline plus half the x-height of the parent.

Aligns the baseline of the element to the given length above the baseline of its parent. A negative value is allowed.

Aligns the baseline of the element to the given percentage above the baseline of its parent, with the value being a percentage of the line-height property. A negative value is allowed.

Line-relative values

The following values vertically align the element relative to the entire line:

Aligns the top of the element and its descendants with the top of the entire line.

Aligns the bottom of the element and its descendants with the bottom of the entire line.

For elements that do not have a baseline, the bottom margin edge is used instead.

Values for table cells

baseline (and sub , super , text-top , text-bottom , , and )

Aligns the baseline of the cell with the baseline of all other cells in the row that are baseline-aligned.

Aligns the top padding edge of the cell with the top of the row.

Centers the padding box of the cell within the row.

Aligns the bottom padding edge of the cell with the bottom of the row.

Negative values are allowed.

Formal definition

Initial value baseline
Applies to inline-level and table-cell elements. It also applies to ::first-letter and ::first-line .
Inherited no
Percentages refer to the line-height of the element itself
Computed value for percentage and length values, the absolute length, otherwise the keyword as specified
Animation type a length

Formal syntax

Examples

Basic example

HTML

div> An img src="frame_image.svg" alt="link" width="32" height="32" /> image with a default alignment. div> div> An img class="top" src="frame_image.svg" alt="link" width="32" height="32" /> image with a text-top alignment. div> div> An img class="bottom" src="frame_image.svg" alt="link" width="32" height="32" /> image with a text-bottom alignment. div> div> An img class="middle" src="frame_image.svg" alt="link" width="32" height="32" /> image with a middle alignment. div> 

CSS

img.top  vertical-align: text-top; > img.bottom  vertical-align: text-bottom; > img.middle  vertical-align: middle; > 

Result

Vertical alignment in a line box

HTML

p> top: img style="vertical-align: top" src="star.png" alt="star"/> middle: img style="vertical-align: middle" src="star.png" alt="star"/> bottom: img style="vertical-align: bottom" src="star.png" alt="star"/> super: img style="vertical-align: super" src="star.png" alt="star"/> sub: img style="vertical-align: sub" src="star.png" alt="star"/> p> p> text-top: img style="vertical-align: text-top" src="star.png" alt="star"/> text-bottom: img style="vertical-align: text-bottom" src="star.png" alt="star"/> 0.2em: img style="vertical-align: 0.2em" src="star.png" alt="star"/> -1em: img style="vertical-align: -1em" src="star.png" alt="star"/> 20%: img style="vertical-align: 20%" src="star.png" alt="star"/> -100%: img style="vertical-align: -100%" src="star.png" alt="star"/> p> 
#*  box-sizing: border-box; > img  margin-right: 0.5em; > p  height: 3em; padding: 0 0.5em; font-family: monospace; text-decoration: underline overline; margin-left: auto; margin-right: auto; width: 80%; > 

Result

Vertical alignment in a table cell

HTML

table> tr> td style="vertical-align: baseline">baselinetd> td style="vertical-align: top">toptd> td style="vertical-align: middle">middletd> td style="vertical-align: bottom">bottomtd> td> p> There is a theory which states that if ever anyone discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable. p> p> There is another theory which states that this has already happened. p> td> tr> table> 

CSS

table  margin-left: auto; margin-right: auto; width: 80%; > table, th, td  border: 1px solid black; > td  padding: 0.5em; font-family: monospace; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 18, 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.

Источник

CSS vertical-align text within a textarea

The following tutorial shows you how to use CSS to do «CSS vertical-align text within a textarea».

CSS Style

The CSS style to do «CSS vertical-align text within a textarea» is

textarea < width:400px; height:400px; padding-top:100px; -webkit-box-sizing:border-box; -moz-box-sizing:border-box; -ms-box-sizing:border-box; -o-box-sizing:border-box; box-sizing:border-box; >

HTML Body

body> textarea id="txt">dsaf sd fsd  

The following iframe shows the result. You can view the full source code and open it in another tab.

html> head> meta name="viewport" content="width=device-width, initial-scale=1"> style id="compiled-css" type="text/css"> textarea!-- w w w .d e mo 2 s . c o m--> width:400px; height:400px; padding-top:100px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; -o-box-sizing: border-box; box-sizing: border-box; >  body> textarea id='txt'>dsaf sd fsd   

  • CSS Unusual shape of a textarea (Demo 5)
  • CSS Using html forms and php for validation on blank textarea or if default value is present
  • CSS Vertical Algin Textarea
  • CSS vertical-align text within a textarea
  • CSS vertical-align text within a textarea (Demo 2)
  • CSS Vertical-align with baseline and textareas
  • CSS Vertical-align with baseline and textareas (Demo 2)

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Как вертикально выровнять заполнитель текста в textarea?

Я пытаюсь вертикально выровнять текст заполнителя в textarea (текстовое поле). Я использую textarea вместо ввода текста, потому что мне нужно использовать несколько строк.

4 ответа

Это работает для последних Firefox, IE/Edge, Chrome в чистом CSS:

textarea < width: 440px; height:600px; /* Note this is the same height as the placeholders line-height */ >::-moz-placeholder < /* Mozilla Firefox 19+ */ line-height:600px; >::-webkit-input-placeholder < /* Webkit */ line-height:600px; >:-ms-input-placeholder < /* IE */ line-height:600px; >

Смотрите fiddle. Ключ должен установить height текстового поля к тому же line-height в качестве заполнителя.

Печально vertical-align: middle; , похоже, пока не поддерживается.

Лучше всего использовать padding , поскольку line height не будет работать над несколькими строками.

Кроме того, при вычислении вашего заполнения обязательно учитывайте размер линии/размер шрифта.

Один из вариантов — использовать line-height :

Вы также можете использовать padding для управления положением текста.

Здесь пример с использованием padding-top

Поскольку требования включают многострочную поддержку, я бы рекомендовал установить верхнее и нижнее дополнение i.e:

Я упустил большую часть кода, чтобы сделать его проще, но когда я это делаю, он просто увеличивает размер текстового поля следующим образом — jsfiddle.net/hb4wqsep

Рассматривая пример текстового поля высотой 600 пикселей, ваше решение будет таким ? Мне немного некрасиво, если пользователь хочет ввести текст .

Я думаю, это не совсем то, что вы хотите, но попробуйте посмотреть..

Чтобы центрировать его по вертикали, я умножаю высоту элемента на 7.5% и делаю его высотой строки.

Примечание. Функция CSS3 calc() работает только в современных браузерах. Вы можете вручную изменить/рассчитать высоту линии, если вы хотите, чтобы она работала в старых браузерах.

или вам действительно нужно использовать jQuery

Ещё вопросы

  • 1 Выполнить ручной откат в среде JTA в EJB без сохранения состояния
  • 0 Ошибка отладки в визуальной студии
  • 0 Javascript — удаление элемента из массива
  • 0 Выберите двойным щелчком или одной буквой div, который делает фокус ввода
  • 0 Компилировать вложенные директивы в модульном тесте в Angular
  • 0 Переменная, выделенная из стека C ++, не уничтожена (/ уничтожена?)
  • 0 JQuery CSS селектор для таблицы
  • 0 MySQL запрос, который меняет идентификатор команды на имя команды и делает не пустым
  • 1 Как рассчитать среднее количество в час?
  • 0 как содержать файл * .tpl в переменной php?
  • 0 Именованные каналы с командной строкой
  • 1 отображать справку, если неверно или опция миссии в клике
  • 0 UI роутер разрешает проблемы
  • 0 PHP время назад (возвращает неверное время)
  • 1 Как применить функцию к нескольким переменным
  • 0 Выберите элемент на основе того, сколько у него детей?
  • 1 Как получить только дату или время только в реакции на нативный
  • 0 Я хочу выбрать каждое значение в раскрывающемся списке, и он будет динамически выполнять модульное тестирование с использованием транспортира
  • 0 Angularjs контрольный отчет о перерыве
  • 0 in_array, похоже, не работает с массивами
  • 0 Скрыть номер мобильного телефона от индексации в Google
  • 0 Как найти ближайшие значения как нижних, так и верхних в массиве объектов в PHP?
  • 0 Отсутствуют заголовочные файлы для Tidy HTML для C
  • 1 Поднять событие, которое передает другое
  • 0 После использования клавиши табуляции не удается прокрутить вверх
  • 1 Есть ли способ отправить письмо из Spotfire одним нажатием кнопки?
  • 0 нет пейджера с использованием ngtable и angularjs
  • 1 Разделить или объединить действия по дате
  • 1 как сохранить настройки приложения и получить их после переустановки или смены устройства
  • 1 Получение значения на основе идентификатора из Enums в Javascript
  • 0 JQGrid: local — jqGrid.trigger («reloadGrid») заставляет исчезать отформатированные данные
  • 1 Тестирование Junit: тестирование всех возможных границ?
  • 0 Angularjs $ ресурс URL-путь
  • 1 Командная строка Java запускается из терминала на Mac. Появляется всплывающее окно Java на панели инструментов Mac, которое исчезает после выполнения заданий.
  • 1 Текстовый редактор с Tkinter Python 3
  • 1 Выберите / Option / Value при изменении, используя Classic ASP
  • 1 Как получить оставшиеся песни и общее время воспроизведения с медиаплеера?
  • 0 Как я могу найти [внутри моего столбца MySQL?
  • 1 Как определить, что для fillStyle был назначен недопустимый цвет?
  • 0 Угловой файл JS скачать
  • 0 Свяжите имя и идентификатор с полем ввода
  • 0 Странное поведение при мониторинге класса по угловой директиве внутри этой директивы
  • 0 Бесконечный цикл Date на одном сервере, но работает на другом и localhost
  • 0 Не работает подпапка движка приложения Google — PHP
  • 1 Сохранение объекта в базе данных приводит к следующему: «На объектный объект нельзя ссылаться несколькими экземплярами IEntityChangeTracker»
  • 0 Код OpenGL Работает в Windows, но не в Mac
  • 1 Как скопировать / повторить массив N раз в новый массив? [Дубликат]
  • 0 Объединение и сортировка 2 каналов
  • 1 Динамическая последовательность точек GPS вдоль дороги

Источник

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