Styling the Content of Textarea Field
A commonly used Perch field type is the Textarea field type.
Textarea represents a multi-line block of text, and is edited with a textarea input field. You can use formatting languages with this textarea and also implement a variety of WYSIWYG editors via our plugin system.
When used without any editors, it returns the raw text as entered (i.e. it won’t apply any HTML to paragraphs):
<perch:content id="text" type="textarea" label="Text">
But I want to discuss styling the output when you are using an editor:
<perch:content id="text" type="textarea" label="Text" markdown editor="simplemde">
Or even just using Makrdown formatting with no editor:
<perch:content id="text" type="textarea" label="Text" markdown>
The problem
If we use Markdown formatting, the following:
# Heading 1
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante.
- list item 1
- list item 2
- list item 3
## Heading 2
Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
Renders to:
<h1>Heading 1</h1>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante.</p>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
</ul>
<h2>Heading 2</h2>
<p>Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
So how do you style this in CSS? You can’t add classes to individual elements like <p class="article_p">
and styling all paragraphs p { }
may apply some styling to other paragraphs in other sections on the website.
Solution
A common practice is to add a div
wrapper around the textarea field:
<div class="content">
<perch:content id="text" type="textarea" label="Text" markdown editor="simplemde">
</div>
This way you can style elements inside .content
. So instead of applying styles to p { }
, you apply styles to .content p { }
:
.content h1 {
}
.content h2 {
}
.content h3 {
}
.content p {
}
.content ul, .content ol {
}
.content li {
}
.content table {
}
.
.
.
You can make use of CSS selectors well here.
.content h1 {
font-size: 2em;
margin-bottom: 0.5em;
}
.content h1:not(first-child) {
margin-top: 1em;
}
.content p:not(:last-child) {
margin-bottom: 0.6em;
}
You can also add modifier classes to control properties like font-size
or color
:
.content h2 {
font-size: 1.3rem;
}
.content.small h2 {
font-size: 0.9rem;
}
.content.large h2 {
font-size: 1.6rem;
}