Loading...

June 16, 2014

Awesome Asciidoctor: Apply Custom Styling to Blocks

To define a listing block to display for example source code in Asciidoc is easy. We can use ---- delimiter or explicitly use [listing] and include the source code. If we use the HTML backend to generate HTML the result will be a pre block enclosed in some div sections with a couple CSS classes applied. If we want to add our own CSS classes to the generated output we can apply so-called roles to our block.

In the following Asciidoc markup we apply a role with the name console to a listing block. Remember we can use the same syntax for other types of blocks as well.

[source,role="console"]
----
$ ls
index.adoc
$
----

If we generate HTML we get the following HTML code. Notice the class attribute of the first div contains console:

<div class="listingblock console">
<div class="content">
<pre class="prettyprint"><code>$ ls
index.adoc
$</code></pre>
</div>
</div>

We can use an alternate syntax which resembles CSS classes closely. We can use dot (.) followed by the role name.

[source.console]
----
$ ls
index.adoc
$
----

If we want to apply multiple roles (CSS classes) we can specify the names separated by spaces in the role attribute or chain the names with .:

[source.console.shell]
----
$ ls
index.adoc
$
----

// Or use role attribute:
[source,role="console shell"]
----
$ ls
index.adoc
$
----

// If we don't apply the source attribute,
// we can still set roles:
[.console]  // Or [role="console"]
----
$ ls
index.adoc
$
----

// If we do not use the delimiter, 
// but specify block type:
[listing.console] // Or [listing,role="console"]
$ ls
index.adoc
$

By specifying role values we can customize how the output looks with different implementation for the CSS classes that we want.

Code generated by Asciidoctor 0.1.4.