- How to style text in your rich text editor
- Basic text styling
- Style text areas with fonts
- Style text area with color
- Style text with alignment and text layout
- Style text areas with more customization
- Синтаксис
- Пример
- Результат
- Пример
- Результат
- Атрибуты
- Как добавить стиль к тегу ?
- Распространенные свойства для изменения визуальной насыщенности/выделения/размера текста внутри тега :
- Цвет текста внутри тега :
- Стили форматирования текста для тега :
- Другие свойства для тега :
- Тег textarea
- Стили по умолчанию
- Атрибуты
- Читайте также
- Обсуждение ( 0 )
How to style text in your rich text editor
A basic textarea tag in a website is useful, up until the point when you need to vary and style text area content. Then, CSS comes to mind as a solution, but if you need something that can change dynamically as customers type into your app’s textarea, complex CSS rules are not the best practice, nor are they effective. Scale issues and time spent creating a solution with JavaScript, HTML, and CSS can impact your planning and budgets.
But there is an easier pathway to style text areas. Instead, adopt a component into your app that can stand in for a basic textarea, and replace it with a diverse collection of text style options. Sounds good? With TinyMCE as your editor component, it’s a straightforward process to integrate the editor and start experimenting with text area style. This article explains how to do it. Let’s begin.
Basic text styling
To try out the basic text styling in the following paragraphs, the following TinyMCE demo can be set up on your development workstation, and then run with a local server with Python or with the PHP command.
First, you need an API key. This key gives you free access to TinyMCE Premium plugins for 14 days. Navigate to the Get-tiny sign up page to get your FREE API key.
You can sign up for an API key, and access advanced typography options using premium plugins. Your API key comes with 14 days free access to Premium plugins, and all TinyMCE skin and icon packs so you can experiment with text area style and find what you need, much faster.
- Create an index.html file.
- With your file open, in the head section, add script tags, and reference TinyMCE Cloud through a CDN link within the script tags. This is what the link looks like:
TinyMCE Quick Start Guide
If you’d like to see something closer to how TinyMCE looks in production, check on the following demo:
With those three steps done, a good starting point to style text areas is fonts.
Style text areas with fonts
First include fonts in the TinyMCE menubar so you can access them easily:
- Clear up the editor’s UI by switching off the menubar, and moving the toolbar to the base of the editor – this places emphasis on what you need to style text areas, and not the toolbar, as the text is the first thing visible:
font_size_formats: "8pt 10pt 12pt 14pt 16pt 18pt 24pt 36pt 48pt";
- To customize fonts, including adding your own selection of fonts, use the font_css and font_family_formats options together. The following example links to some Google fonts (You can access and import Google fonts from the fonts.google website – click “view selected families” to check on your collected fonts):
//Font Text Area Style font_css: '@import url("https://fonts.googleapis.com/css2?family=Open+Sans&family=Roboto&display=swap");', font_family_formats: 'Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Arial Black=arial black,avant garde; Book Antiqua=book antiqua,palatino; Courier New=courier new,courier; Georgia=georgia,palatino; Helvetica=helvetica; Impact=impact,chicago; Symbol=symbol; Tahoma=tahoma,arial,helvetica,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Open Sans=open sans,sans-serif; Roboto=roboto,regular,sans-serif;'
After you save the changes, you can style text area content with different fonts in your demo with TinyMCE:
Style text area with color
To change the colors of the text you’re entering into the text area, there are several options you can configure:
- color_cols – An option used to adjust the number of columns displayed in the TinyMCE color picker
- color_map – used to configure the exact colors you’d like to appear in the color map
- hilitecolor – You can use this format option to set up a specific color for the text highlighter
- custom_colors – this is an option that accepts a true or false value to turn on or off the ability to make custom colors for the text.
Here’s how some of the options (namely color_cols and color_map) work in practice:
//Color Text Area Style color_cols: , color_map: [ ],
- Configure the number of columns and the specific colors for your text area style. Here’s one example to try out:
//Color Text Area Style color_cols: 6, color_map: [ '#F0F8FF', 'aliceblue', '#FAEBD7', 'antiquewhite', '#F0FFFF', 'azure', '#FFEBCD', 'blanchedalmond', '#DEB887', 'burlywood', '#7FFF00', 'chartreuse', '#DC143C', 'crimson', ],
Style text with alignment and text layout
In TinyMCE, styling text through alignment is made easier with the “align” options clearly placed on the default toolbar. You can create layouts by making use of blocks. The default blocks available include:
Here’s how to make some adjustments to the Alignment and Text Layout options:
toolbar: 'undo redo formatpainter | alignleft aligncenter alignright alignjustify | blocks fontfamily fontsize | bold italic underline forecolor backcolor | lineheight | removeformat',
- Add the visual blocks plugin to the toolbar. This plugin helps with text area style by revealing the block layouts:
toolbar: 'undo redo formatpainter | visualblocks | alignleft aligncenter alignright alignjustify | blocks fontfamily fontsize | bold italic underline forecolor backcolor | lineheight | removeformat',
//Alignment and Layout for Text Area Style block_formats: "Paragraph=p; Header 1=h1; Header 2=h2; Header 3=h3; Code=code";
Style text areas with more customization
These are some of the essential methods for customizing and modifying the text area style options available with TinyMCE. But there is much more available for you to set up different styles and looks for your customers to try out in your app. For instance:
There’s a diverse world of possibilities out there, and you can reach out to us to talk about how TinyMCE can work in your application.
HTML тег
Между открывающим тегами можно поместить любой текст, который будет отображаться моноширинным начертанием. В текстовое поле можно вводить любое количество символов.
Синтаксис
Содержимое элемента заключается между открывающим () тегами.
Для определения размера текстового поля можно использовать атрибуты cols и rows , или же использовать CSS свойства height и width . А с помощью CSS свойства resize можно запретить изменение размера текстового поля.
Пример
html> html> head> title>Заголовок документа title> head> body> form> textarea name="comment" rows="12" cols="35">Написать комментарий автору. textarea>br> input type="submit" name="submitInfo" value="Отправить"> form> body> html>
Результат
В этом примере мы определили текстовую область тегом , присвоили ей имя “comment”, использовав атрибут name ; задали высоту строк (12 символов) атрибутом rows и указали ширину поля атрибутом cols (35 символов). Мы также разместили внутри формы кнопку, при нажатии на которую введенная информация отправляется на сервер.
Пример
html> html> head> title>Заголовок документа title> style> .comment < width: 60%; height: 100px; padding: 10px; outline: 0; border: 3px solid #1c87c9; background: #d0e2bc; line-height: 20px; > style> head> body> form> p>Пример с использованием CSS стилей p> textarea class="comment"> Написать комментарий автору. textarea> br> input type="submit" name="submitInfo" value="Отправить"> form> body> html>
Результат
В этом примере мы использовали CSS стили для визуального оформления текстового поля.
Атрибуты
Атрибут | Значение | Описание |
---|---|---|
autocomplete | on off | Определяет, может ли содержимое элемента быть автоматически дополнено браузером (автозаполнение). |
autofocus | autofocus | Указывает, что текстовая область должна автоматически получать фокус при загрузке страницы. |
cols | number | Определяет видимую ширину текстовой области (в символах). Значение по умолчанию 20 символов. |
dirname | textareaname.dir | Определяет и передает на сервер направление текста. |
disabled | disabled | Логический атрибут, указывающий, что текстовая область должна быть отключена. |
form | form_id | Определяет одну или несколько форм, к которым принадлежит элемент и связывает их при помощи идентификатора (id). |
maxlenght | number | Указывает максимальное количество символов, которое может содержать текстовая область. |
minlength | number | Указывает минимальное количество символов, которое может содержать текстовая область. |
name | text | Определяет имя текстового поля. |
placeholder | text | Указывает текст подсказки, которая описывает ожидаемое значение для ввода пользователем в элемент. Подсказка отображается в пустом текстовом поле, и исчезнет при получение им фокуса. |
readonly | readonly | Указывает, что текстовая область доступна только для чтения. |
required | required | Логический атрибут, указывающий, что текстовая область должна быть заполнена перед отправлением формы. |
rows | number | Определяет видимое количество строк в текстовой области. Значение по умолчанию 2 символа. |
wrap | Определяет, как текст должен быть перенесен, когда отправляется форма. | |
soft | -(значение по умолчанию) текст отправляется одной сплошной строкой без добавления дополнительных переносов строк. | |
hard | -браузер автоматически вставляет разрывы строки так, что каждая строка не будет шире текстового поля. Используется только если установлен атрибут cols. |
Как добавить стиль к тегу ?
Распространенные свойства для изменения визуальной насыщенности/выделения/размера текста внутри тега :
- CSS свойство font-style задает стиль шрифта: normal | italic | oblique | initial | inherit
- CSS свойство font-family создает приоритетный список названий семейства шрифтов и/или общее имя шрифтов для выбранных элементов.
- CSS свойство font-size задает размер щрифта.
- CSS свойство font-weight устанавливает насыщенность шрифта.
- CSS свойство text-transform задает регистр текста (заглавные или строчные буквы).
- CSS свойство text-decoration устанавливает оформление текста. Оно является сокращенным свойством для text-decoration-line, text-decoration-color, text-decoration-style.
Цвет текста внутри тега :
Стили форматирования текста для тега :
- CSS свойство text-indent указывает размер отступа первой строки в текстовом блоке.
- CSS свойство text-overflow указывает, как будет отображаться пользователю строчный текст, выходящий за границы блока.
- CSS свойство white-space указывает, как будут отображены пробелы внутри элемента.
- CSS свойство word-break указывает перенос строки.
Другие свойства для тега :
- CSS свойство text-shadow добавляет тень к тексту.
- CSS свойство text-align-last выравнивает последнюю строку текста.
- CSS свойство line-height устанавливает межстрочный интервал.
- CSS свойство letter-spacing устанавливает расстояние между буквами/символами в тексте.
- CSS свойство word-spacing устанавливает расстояние между словами в тексте.
Тег textarea
Создает текстовое поле для ввода большого количества информации. Используется при работе с формами.
Стили по умолчанию
Стили которые браузер применяет к элементу по-умолчанию. В списке ниже приведены стили, которые влияют на внешний вид элемента и изменяются при помощи CSS.
Атрибуты
Уникальное имя текстового поля. Используется для получения значений на сервере.
Текст внутри поля, который определяет что это за поле. Текст виден только если поле пустое.
Указывает что поле обязательно для заполнения. Браузерная проверка.
Поле недоступно для заполнения.
Устанавливает фокус в данное поле по умолчанию при загрузке страницы.
Поле только для чтения. Ввод запрещен.
Указывает последовательность перехода по полям формы при нажатии на кнопку tab. Указывается целое положительное либо отрицательное число.
Минимальное количество символов, которое необходимо ввести пользователю.
Максимальное количество символов, которое может ввести пользователь.
Определяет ширину поля. Указывается целое число, значение по умолчанию 20. Рекомендуется использовать стилизацию через CSS для обозначения размеров поля.
Определяет высоту поля. Указывается целое число. Рекомендуется использовать стилизацию через CSS для обозначения размеров поля.
Читайте также
ссылка боковая панель блочный контейнер курсивный текст группа полей формы заголовок для figure контейнер для изображения заголовок четвертого уровня встраивание страниц значение в диапазоне элемент выпадающего списка выпадающий список строчная обертка стили документа «тело» таблицы
Обсуждение ( 0 )
Войдите или зарегистрируйтесь для того чтобы оставлять комментарии