ラベル CSS の投稿を表示しています。 すべての投稿を表示
ラベル CSS の投稿を表示しています。 すべての投稿を表示

2018年1月6日土曜日

目次を動的に生成する方法

このブログでは記事本文から目次を動的に生成して記事の前に表示しています。 このブログで行っている目次の動的生成方法をご紹介します。

目次を動的に生成する前提条件

記事本文から目次を動的に生成するには、記事本文に仕掛けが必要です。 その仕掛けは、このブログの記事である 「HTMLの見出しタグに連番を振るCSSの書き方」 でご紹介したように、記事中の見出しとする文章をh4~h6のHTMLタグで括り、そのclass属性値にそれぞれ、foacs-chapter、foacs-section、foacs-paragraphの値を設定します。

下記のような記述が記事本文に必要で、hタグで括られた文章を使って目次を動的に生成します。

<h4 class="foacs-chapter">章の見出し01</h4>

<p>章の文章01</p>

<h5 class="foacs-section">節の見出し0101</h5>

<p>節の文章0101</p>

<h6 class="foacs-paragraph">項の見出し010101</h6>

<p>項の文章010101</p>

これからご紹介する動的に目次を生成する方法で対応しているのは「章(foacs-chapter)」「節(foacs-section)」「項(foacs-paragraph)」の3段階のみです。

ちなみに、「foacs」はこのブログの英語名(灰色スズメの足跡=footprints of ash color sparrow)の単語の頭文字をつなげたもので、Bloggerで元から使用されている他のクラス名と重複しないように使用している接頭辞です。

目次を動的に生成する仕掛け

目次を動的に生成する仕掛けはJavaScriptで作っています。 そのプログラムについてご説明します。

目次を動的に生成するJavaScript

目次を動的に生成するJavaScriptのプログラムは下記のとおりです。 下記の目次生成関数は記事本文中のh4タグのclass属性値「foacs-chapter(章)」、h5タグのclass属性値「foacs-section(節)」、h6タグのclass属性値「foacs-paragraph(項)」を探して目次を生成します。

// 目次生成関数。
function generateContents()
{
  // 記事の表示要素一覧を取得。
  // Bloggerは2017年10月の記事一覧のように複数の記事表示ができる。
  const postBodies = document.body.getElementsByClassName('post-body entry-content');

  // 記事ごとに目次を生成する。
  for (let postBody = 0; postBody < postBodies.length; postBody++)
  {
    // 記事内にfoacs-chapterをクラス属性値に持つ要素があれば目次を生成する。
    if (0 < postBodies[postBody].getElementsByClassName('foacs-chapter').length)
    {
      // 目次生成。
      let htmlContents = `<div class='foacs-contents'><ol>`;

      let chapter = 0, section = 0, paragraph = 0;

      for (let childPostBody of postBodies[postBody].children)
      {
        if (childPostBody.className == 'foacs-chapter')
        {
          if (paragraph != 0)
          {
            htmlContents += `</li></ol>`;
            paragraph = 0;
          }
          if (section != 0)
          {
            htmlContents += `</li></ol>`;
            section = 0;
          }
          if (chapter != 0)
          {
            htmlContents += `</li>`;
          }

          chapter++;
        }

        if (childPostBody.className == 'foacs-section')
        {
          if (paragraph != 0)
          {
            htmlContents += `</li></ol>`;
            paragraph = 0;
          }
          if (section != 0)
          {
            htmlContents += `</li>`;
          }

          if (section == 0)
          {
            htmlContents += `<ol>`;
          }

          section++;
        }

        if (childPostBody.className == 'foacs-paragraph')
        {
          if (paragraph != 0)
          {
            htmlContents += `</li>`;
          }

          if (paragraph == 0)
          {
            htmlContents += `<ol>`;
          }

          paragraph++;
        }

        if (childPostBody.className == 'foacs-chapter' || childPostBody.className == 'foacs-section' || childPostBody.className == 'foacs-paragraph')
        {
          childPostBody.id = `foacs-heading-${postBody}-${chapter}-${section}-${paragraph}`;
          htmlContents += `<li><a href='#foacs-heading-${postBody}-${chapter}-${section}-${paragraph}' title='${childPostBody.textContent}'>${childPostBody.textContent}</a>`;
        }
      }

      if (paragraph != 0)
      {
        htmlContents += `</li></ol>`;
        paragraph = 0;
      }
      if (section != 0)
      {
        htmlContents += `</li></ol>`;
        section = 0;
      }
      if (chapter != 0)
      {
        htmlContents += `</li></ol>`;
        chapter = 0;
      }

      htmlContents += `</div>`;

      for (let postHeader of postBodies[postBody].parentElement.getElementsByClassName('post-header'))
      {
        // 既存の目次を削除する。
        for (let foacsContents of postHeader.getElementsByClassName("foacs-contents"))
        {
          if (foacsContents.parentNode)
          {
            foacsContents.parentNode.removeChild(foacsContents);
          }
        }

        // 記事本文の前にある記事ヘッダー要素に生成した目次を追記する。
        postHeader.innerHTML += htmlContents;
      }
    }
  }
}

上記の目次生成関数をBloggerレイアウト用HTMLに挿入して保存しておくと、目次生成関数はBloggerのすべての記事に対して目次を生成して表示します。

Bloggerレイアウト用HTMLに目次生成関数を挿入して保存する

目次生成関数は下記のようにBloggerレイアウト用HTMLに挿入します。

Blogger設定画面で、

  1. [テーマ]の編集画面を表示

    Blogger設定画面
  2. [HTMLの編集]ボタンを押下

    Bloggerレイアウト用HTML
  3. テキストボックス中のBloggerレイアウト用HTMLのbodyタグの終了タグの直前にscriptタグがあるので、 そこに上記の目次生成関数と呼び出し処理である下記のコードを挿入します。
    document.addEventListener('DOMContentLoaded', generateContents());
    上記のコードは、HTML文書の読み込みが終了した時に目次生成関数generateContentsを呼び出すという意味です。
    Bloggerレイアウト用HTMLは下記のようになります。

    
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
          <div class='content-cap-bottom cap-bottom'>
            <div class='cap-left' />
            <div class='cap-right' />
          </div>
        </div>
      </div>
    
      <script type='text/javascript'>
        window.setTimeout(function () {
          document.body.className = document.body.className.replace(' loading ', '');
        }, 10);
    
        // Insert Begin by foacs
        //<![CDATA[
        document.addEventListener('DOMContentLoaded', generateContents());
    
    
        // 目次生成関数。
        function generateContents()
        {
          // 記事の表示要素一覧を取得。
          // Bloggerは2017年10月の記事一覧のように複数の記事表示ができる。
          const postBodies = document.body.getElementsByClassName('post-body entry-content');
    
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
                // 記事本文の前にある記事ヘッダー要素に生成した目次を追記する。
                postHeader.innerHTML += htmlContents;
              }
            }
          }
        }
        //]]>
        // Insert End by foacs
      </script>
    </body>
    
    <macro:includable id='sections' var='col'>
      <macro:if cond='data:col.num == 0'>
        <macro:else/>
        <b:section mexpr:class='data:col.class' mexpr:id='data:col.idPrefix + "-1"' preferred='yes' showaddelement='yes'
        />
    
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    
  4. [テーマを保存]ボタンを押下して、Bloggerレイアウト用HTMLをBloggerに保存する

目次生成関数が生成するHTML

目次生成関数は下記の記事本文のHTMLを読み込み、

<h4 class="foacs-chapter">章の見出し01</h4>

<p>章の文章01</p>

<h5 class="foacs-section">節の見出し0101</h5>

<p>節の文章0101</p>

<h6 class="foacs-paragraph">項の見出し010101</h6>

<p>項の文章010101</p>

記事本文のHTMLから下記の目次のHTMLを生成します。

<div class="foacs-contents">
<ol>
    <li>
        <a href="#foacs-heading-0-1-0-0" title="章の見出し01">章の見出し01</a>
        <ol>
            <li>
                <a href="#foacs-heading-0-1-1-0" title="節の見出し0101">節の見出し0101</a>
                <ol>
                    <li>
                        <a href="#foacs-heading-0-1-1-1" title="項の見出し010101">項の見出し010101</a>
                    </li>
                </ol>
            </li>
        </ol>
    </li>
</ol>
</div>

生成した目次にはaタグにより記事内の当該箇所にリンクが張ってあります。 目次生成関数は目次のリンク先の記事本文のhタグに移動できるように、記事本文のhタグにid属性と属性値を追加します。

目次を挿入する箇所

目次生成関数は生成した目次HTMLをBloggerが用意しているclass属性値がpost-headerのdivタグの子要素として挿入します。 目次生成関数はBlogger記事ページに目次HTMLを下記のように挿入します。 Chrome DevTools で確認してみてください。


<div class="post hentry uncustomized-post-template" itemprop="blogPost" itemscope="itemscope" itemtype="http://schema.org/BlogPosting">

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    <h3 class="post-title entry-title" itemprop="name">
        記事題名
    </h3>
    <div class="post-header">
        <div class="post-header-line-1"></div>
        ★目次生成関数が目次HTMLを挿入する箇所★
    </div>
    <div class="post-body entry-content" id="post-body-xxxxx" itemprop="description articleBody">

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
記事本文
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        <div style="clear: both;"></div>
    </div>
    <div class="post-footer">

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    </div>
</div>

目次を修飾するCSS

目次を修飾するCSSは下記のとおりです。

/*
目次設定
*/
.foacs-contents
{
    border: 1px solid var(--foacs-foreground-color);
    font-size: medium;
    margin: 4em auto;
    padding: 2em;
}

.foacs-contents::before
{
    content: "目次";
    font-size: larger;
}

.foacs-contents > ol
{
    counter-reset: --foacs-chapter-counter;
    counter-reset: --foacs-section-counter;
    counter-reset: --foacs-paragraph-counter;

    list-style-type: none;
    padding: 0;
}

.foacs-contents li
{
    line-height: 2em;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.foacs-contents > ol > li
{
    counter-increment: --foacs-chapter-counter;
    counter-reset: --foacs-section-counter;
}

.foacs-contents > ol > li::before
{
    content: counter(--foacs-chapter-counter) ".";
    padding-right: 0.5em;
}

.foacs-contents > ol > li > ol > li
{
    counter-increment: --foacs-section-counter;
    counter-reset: --foacs-paragraph-counter;
}

.foacs-contents > ol > li > ol > li::before
{
    content: counter(--foacs-chapter-counter) "." counter(--foacs-section-counter) ".";
    padding-right: 0.5em;
}

.foacs-contents > ol > li > ol > li > ol > li
{
    counter-increment: --foacs-paragraph-counter;
}

.foacs-contents > ol > li > ol > li > ol > li::before
{
    content: counter(--foacs-chapter-counter) "." counter(--foacs-section-counter) "." counter(--foacs-paragraph-counter) ".";
    padding-right: 0.5em;
}

上記のCSSは下記のようにBloggerに追加します。

Blogger設定画面で、

  1. [テーマ]の編集画面を表示

    Blogger設定画面
  2. [カスタマイズ]ボタンを押下

  3. Bloggerテーマデザイナーで[上級者向け]ー[CSSを追加]を選択

    BloggerテーマデザイナーCSSを追加
  4. テキストボックス内にカスタムCSSを追記する

  5. 画面右上の[ブログに適用]ボタンを押下して、カスタムCSSをBloggerに追加する

記事終わり

2017年12月11日月曜日

Google code-prettifyのBloggerへの導入方法

このブログではプログラムのソースコードを色分け表示するためにGoogle code-prettifyを使用しています。 code-prettifyを使うとソースコードを構文に従い、判り易く色分け表示してくれます。

Bloggerでcode-prettifyを使用する方法をご紹介します。

code-prettify導入手順

code-prettifyはGitHubで公開されています。
Google code-prettify

code-prettify公式の導入手順も公開されています。
code-prettify/docs/getting_started.md

code-prettifyの詳細はGitHubのcode-prettifyのページを参照してください。 ここではBloggerへの導入に絞ってご説明します。

Bloggerでcode-prettifyを導入する手順は下記の3つです。

  1. Bloggerへcode-prettifyのJavaScriptを読み込ませる
  2. ソースコードをpreタグで括る
  3. Bloggerへソースコードの見た目を設定するCSSを追加する

これらの手順についてご説明します。

Bloggerへcode-prettifyのJavaScriptを読み込ませる

code-prettifyはJavaScriptとCSSで出来ています。 まずは、code-prettifyのJavaScriptをBloggerへ読み込ませます。

そのために下記の手順を踏みます。

Bloggerの設定画面で、

  1. [テーマ]の編集画面を表示
  2. [HTMLの編集]ボタンを押下

Bloggerのレイアウト用HTMLがテキストボックスに表示されますので、head終了タグ(</head>)の直前に下記のscriptタグを挿入して、code-prettifyのJavaScriptをBloggerに読み込ませます。

<script src='https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js' type='text/javascript' />

これで、下記の拡張子のプログラミング言語は色分け表示できます。
"bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html", "java", "js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh", "xhtml", "xml", "xsl".

上記以外のプログラミング言語を色分け表示したいのであれば、scriptタグのsrc属性値のrun_prettify.jsの後に「?lang=」と付け加えて、code-prettifyに色分け表示させたいプログラミング言語を指定します。

例えばExcel VBAとCSSを色分け表示させたければ下記のようにします。

  ...
  <script src='https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?lang=vb&lang=css' type='text/javascript' />
</head>
...

lang=xxxのxxxにはプログラミング言語を示す文字列を指定します。指定可能な文字列は下記Webページをご参照ください。
index of language handlers

これでcode-prettifyのJavaScriptをBloggerへ読み込ませる手順は完了です。

ソースコードをpreタグで括る

code-prettifyでソースコードを色分け表示するためには、下記のようにソースコードをpreタグで括り、class属性値にprettyprintを指定します。

<pre class="prettyprint lang-xxx linenums">
ソースコード
</pre>

HTMLの文書構造の構成を意味させるためにソースコードをcodeタグで括りたいという方は、下記のようにpreタグの内側にcodeタグを設置してもcode-prettifyで色分け表示できます。
このcodeタグは表示されず、見た目に影響を与えません。

<pre class="prettyprint lang-xxx linenums">
<code>
ソースコード
</code>
</pre>
preタグのclass属性値
<pre class="prettyprint lang-xxx linenums">
prettyprint

preタグのclass属性値にprettyprintがあることで、preタグで括られたソースコードはcode-prettifyにより色分け表示されます。

lang-xxx

lang-xxxのxxxには下記のプログラミング言語の拡張子を示す文字列を指定します。
"bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html", "java", "js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh", "xhtml", "xml", "xsl".

上記以外の指定可能な文字列は下記Webページをご参照ください。
index of language handlers

HTMLならlang-html、CSSならlang-css、JavaScriptならlang-jsとなります。

色分け表示させたいプログラミング言語が上記の一覧にない場合、プログラミング言語の構文規則が近いものを指定します。 例えば、Excel VBAは上記の一覧に存在しないので、構文規則の近いVisual Basicを指定します(lang-vb)。

linenums

linenumsを指定すると行番号を表示できます。 行番号は1から始まりますが、下記のように番号を指定するとその番号から始まるようになります。
linenums:10
上記のように書くと行番号は10から始まります。

code-prettifyが生成するHTML

code-prettifyはprettyprintをclass属性値に持つpreタグ内のソースコードを読み込んでHTMLを生成します。 preタグとその中のソースコードはそのHTMLで置き換えられます。

code-prettifyは下記のpreタグで括られたソースコードを読み込みます。

<pre class="prettyprint lang-js linenums">
function testFunction()
{
    const testMessage = "TEST";
    alert(testMessage);
    return;
}
</pre>

そして、code-prettifyは読み込んだソースコードから下記のHTMLを生成して置き換えます。

<pre class="prettyprint lang-js linenums prettyprinted" style="">
    <ol class="linenums">
        <li class="L0">
            <span class="kwd">function</span>
            <span class="pln"> testFunction</span>
            <span class="pun">()</span>
        </li>
        <li class="L1">
            <span class="pun">{</span>
        </li>
        <li class="L2">
            <span class="pln">    </span>
            <span class="kwd">const</span>
            <span class="pln"> testMessage </span>
            <span class="pun">=</span>
            <span class="pln"> </span>
            <span class="str">"TEST"</span>
            <span class="pun">;</span>
        </li>
        <li class="L3">
            <span class="pln">    alert</span>
            <span class="pun">(</span>
            <span class="pln">testMessage</span>
            <span class="pun">);</span>
        </li>
        <li class="L4">
            <span class="pln">    </span>
            <span class="kwd">return</span>
            <span class="pun">;</span>
        </li>
        <li class="L5">
            <span class="pun">}</span>
        </li>
    </ol>
</pre>

上記のcode-prettifyが出力したHTMLを念頭に置きながら、追加するCSSの説明をお読みください。

Bloggerへソースコードの見た目を設定するCSSを追加する

code-prettifyはソースコードの色分け表示などの見た目に関する設定をCSSで行っています。 CSSの設定方法には2通りあり、テーマと呼ばれる既存設定を読み込む方法と独自のCSSで指定する方法があります。

Bloggerへcode-prettifyのテーマを読み込ませる

code-prettifyには見た目の設定をまとめたテーマがあらかじめ何種類かあり、scriptタグのJavaScriptの読み込み箇所で指定できます。
あらかじめ用意されているテーマは下記をご参照ください。
Gallery of themes for code prettify

scriptタグで上記のテーマを読み込むには下記のように「skin=」を追加します。

<script src='https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?lang=vb&lang=css&skin=desert' type='text/javascript' />

「skin=」に続くテーマの名前はすべて小文字で指定してください。

code-prettifyのCSS

このブログでは既存のテーマは一切使わずに必要なものは独自のCSSで指定しています。
CSSで指定する方法をご紹介します。

CSSの内容

code-prettifyの見た目を設定するCSSは下記になります。
下記のCSSはcode-prettifyのDefaultテーマのCSSを改造したものです。

/*
Google code-prettify
*/
pre.prettyprint
{
    border: 1px solid #cccccc !important;
    line-height: 1.5em;
    overflow: auto;
    padding: 2em !important;
}

pre.prettyprint > ol.linenums
{
    padding-left: 2em;
}

pre.prettyprint > ol.linenums > li
{
    border-left: 1px solid #cccccc;
    margin-bottom: 0;
}

pre.prettyprint > ol.linenums > li.L0,
pre.prettyprint > ol.linenums > li.L1,
pre.prettyprint > ol.linenums > li.L2,
pre.prettyprint > ol.linenums > li.L3,
pre.prettyprint > ol.linenums > li.L4,
pre.prettyprint > ol.linenums > li.L5,
pre.prettyprint > ol.linenums > li.L6,
pre.prettyprint > ol.linenums > li.L7,
pre.prettyprint > ol.linenums > li.L8,
pre.prettyprint > ol.linenums > li.L9 
{
    list-style-type: decimal;
}

pre.prettyprint > ol.linenums > li.L1,
pre.prettyprint > ol.linenums > li.L3,
pre.prettyprint > ol.linenums > li.L5,
pre.prettyprint > ol.linenums > li.L7,
pre.prettyprint > ol.linenums > li.L9 
{
    background-color: transparent;
}

pre.prettyprint > ol.linenums > li span:first-child
{
    padding-left: 1em;
}

pre.prettyprint > ol.linenums > li span:last-child
{
    padding-right: 1em;
}

/* plain text */
pre.prettyprint .pln { color: #cccccc; }

/* string content */
pre.prettyprint .str { color: #cccc33; }
/* a keyword */
pre.prettyprint .kwd { color: #00cc00; }
/* a comment */
pre.prettyprint .com { color: #cc3366; }
/* a type name */
pre.prettyprint .typ { color: #00cc00; }
/* a literal value */
pre.prettyprint .lit { color: #3399cc; }
/* punctuation, lisp open bracket, lisp close bracket */
pre.prettyprint .pun,
pre.prettyprint .opn,
pre.prettyprint .clo
{ color: #cccccc; }
/* a markup tag name */
pre.prettyprint .tag { color: #3399cc; }
/* a markup attribute name */
pre.prettyprint .atn { color: #00cc00; }
/* a markup attribute value */
pre.prettyprint .atv { color: #cccc33; }
/* a declaration; a variable name */
pre.prettyprint .dec,
pre.prettyprint .var
{ color: #00cc00; }
/* a function name */
pre.prettyprint .fun { color: #cc66cc; }
pre.prettyprint
pre.prettyprint
{
    border: 1px solid #cccccc !important;
    line-height: 1.5em;
    overflow: auto;
    padding: 2em !important;
}

code-prettifyでソースコードを色分け表示するには、ソースコードをpreタグで括り、そのpreタグのclass属性値にprettyprintを指定します。

code-prettifyはscriptタグのskinでテーマを指定しなくても初期設定のCSSを読み込んでいます。 上記の!importantの設定はcode-prettifyの初期設定を上書きするために必要です。 code-prettifyの初期設定で設定されていない項目は、!importantの指定がなくてもCSSの設定が反映されます。

このCSSは、prettyprintを属性値に持つpreタグに枠線を引いて、行の高さを1.5emにして、画面からはみ出したらブラウザで自動処理して、パディングを2emにするように設定しています。

pre.prettyprint > ol.linenums
pre.prettyprint > ol.linenums
{
    padding-left: 2em;
}

code-prettifyでは行番号の表示ができます。 code-prettifyで行番号を表示するにはpreタグのclass属性値にlinenumsを指定します。

上記は、linenumsを属性値に持つolタグの左側に2emのパディングを入れるように設定しています。 この設定がないとolタグの標準的な左側のパディングが入ってしまい、隙間が空きすぎる見た目になってしまいます。

code-prettifyが行番号を表示する場合に生成するHTMLは、preタグの内側にolタグのリストを入れる形式となります。

<pre class="prettyprint lang-js linenums prettyprinted" style="">
    <ol class="linenums">
        ...
    </ol>
</pre>
pre.prettyprint > ol.linenums > li
pre.prettyprint > ol.linenums > li
{
    border-left: 1px solid #cccccc;
    margin-bottom: 0;
}

行番号を表示する際に、行番号とソースコードの間に縦線を引いています。

margin-bottom: 0は、Bloggerの初期設定CSSのmargin-bottom: 0.25emを無効にするために指定しています。 margin-bottom: 0を指定しないと行番号とソースコードの間の縦線が点線のようになってしまいます。

pre.prettyprint > ol.linenums > li.L0

preタグに行番号を表示する指定(linenums)をするとcode-prettifyは下記のようなHTMLを出力します。

<pre class="prettyprint lang-js linenums prettyprinted" style="">
    <ol class="linenums">
        <li class="L0">...</li>
        <li class="L1">...</li>
        ...
        <li class="L9">...</li>
        <li class="L0">...</li>
        ...
    </ol>
</pre>

ソースコードの1行を1つのliタグで括っています。 liタグのclass属性値はL0~L9となっていて、ソースコードの行数分だけ繰り返しています。

code-prettifyがこのようなHTMLを出力することを踏まえて以下の説明をお読みください。

pre.prettyprint > ol.linenums > li.L0,
pre.prettyprint > ol.linenums > li.L1,
pre.prettyprint > ol.linenums > li.L2,
pre.prettyprint > ol.linenums > li.L3,
pre.prettyprint > ol.linenums > li.L4,
pre.prettyprint > ol.linenums > li.L5,
pre.prettyprint > ol.linenums > li.L6,
pre.prettyprint > ol.linenums > li.L7,
pre.prettyprint > ol.linenums > li.L8,
pre.prettyprint > ol.linenums > li.L9 
{
    list-style-type: decimal;
}

このCSS設定をしないと、5行ごとに行番号が表示されるようになります。 すべての行に行番号を表示するためにli.L0~li.L9にlist-style-type: decimalを設定しています。

pre.prettyprint > ol.linenums > li.L1,
pre.prettyprint > ol.linenums > li.L3,
pre.prettyprint > ol.linenums > li.L5,
pre.prettyprint > ol.linenums > li.L7,
pre.prettyprint > ol.linenums > li.L9 
{
    background-color: transparent;
}

行番号を表示する際にcode-prettifyは初期設定CSSで、奇数行の背景色を#eeeeeeという淡い灰色にしてしまいます。 これを無効にするためにbackground-color: transparentを設定しています。

pre.prettyprint > ol.linenums > li span
pre.prettyprint > ol.linenums > li span:first-child
{
    padding-left: 1em;
}

pre.prettyprint > ol.linenums > li span:last-child
{
    padding-right: 1em;
}

行番号を表示する際に、ソースコードの左と右に1emのパディングを入れています。 これを入れないとソースコードと枠線の間に余白がなくなり、窮屈な見た目になってしまいます。

liタグとspanタグの間のCSSセレクタ指定を子セレクタ(>)ではなく子孫セレクタ(空白)にしているのは、preタグの内側にcodeタグを指定した場合を考慮してのことです。

ソースコードを表示する際にpreタグのみで括った場合は、

<pre class="prettyprint lang-xxx linenums">
function testFunction()
...
</pre>

code-prettifyは下記のHTMLを出力します。

<pre class="prettyprint lang-js linenums prettyprinted" style="">
    <ol class="linenums">
        <li class="L0">
            <span class="kwd">function</span>
            <span class="pln"> testFunction</span>
            <span class="pun">()</span>
        </li>
        ...
    </ol>
</pre>

ソースコードを表示する際にpreタグの内側にcodeタグを指定した場合は、

<pre class="prettyprint lang-xxx linenums">
<code>
function testFunction()
...
</code>
</pre>

code-prettifyは下記のHTMLを出力します。

<pre class="prettyprint lang-js linenums prettyprinted" style="">
    <ol class="linenums">
        <li class="L0">
            <code>
                <span class="kwd">function</span>
                <span class="pln"> testFunction</span>
                <span class="pun">()</span>
            </code>
        </li>
        ...
    </ol>
</pre>

preタグのみで括った場合とpreタグとcodeタグで括った場合の両方に対応するために、liタグとspanタグは子孫セレクタで設定しています。

これらのCSSにより、上記の2通りのHTMLで<span class="kwd">function</span>の左側に1emのパディングを入れて、<span class="pun">()</span>の右側に1emのパディングを入れています。
li span:first-childは、liタグの子孫の最初のspanタグという意味です。
li span:last-childは、liタグの子孫の最後のspanタグという意味です。
liの子孫にspanタグが1つしかない場合は、最初と最後のspanタグがその1つしかないspanタグになるので、その1つしかないspanタグの左右に1emのパディングが入るようになります。

pre.prettyprint .xxx

code-prettifyは下記のソースコードをプログラミング言語の構文に従って字句に分解して、その字句ごとにspanタグで括ります。

function testFunction()
{
    ...
}
<pre class="prettyprint lang-js linenums prettyprinted" style="">
    <ol class="linenums">
        <li class="L0">
            <span class="kwd">function</span>
            <span class="pln"> testFunction</span>
            <span class="pun">()</span>
        </li>
        ...
    </ol>
</pre>

このspanタグにはプログラミング言語の構文規則に基づいた字句の種別を示すclass属性値が設定されているので、そのclass属性値に応じて色分け表示のCSSを設定していきます。

その色分け表示のCSSの設定が下記のCSSです。

/* plain text */
pre.prettyprint .pln { color: #cccccc; }

/* string content */
pre.prettyprint .str { color: #cccc33; }
/* a keyword */
pre.prettyprint .kwd { color: #00cc00; }
/* a comment */
pre.prettyprint .com { color: #cc3366; }
/* a type name */
pre.prettyprint .typ { color: #00cc00; }
/* a literal value */
pre.prettyprint .lit { color: #3399cc; }
/* punctuation, lisp open bracket, lisp close bracket */
pre.prettyprint .pun,
pre.prettyprint .opn,
pre.prettyprint .clo
{ color: #cccccc; }
/* a markup tag name */
pre.prettyprint .tag { color: #3399cc; }
/* a markup attribute name */
pre.prettyprint .atn { color: #00cc00; }
/* a markup attribute value */
pre.prettyprint .atv { color: #cccc33; }
/* a declaration; a variable name */
pre.prettyprint .dec,
pre.prettyprint .var
{ color: #00cc00; }
/* a function name */
pre.prettyprint .fun { color: #cc66cc; }

.plnは通常の文字列、.strは引用符で括られた文字列、.comはコメントなどとなっています。

colorしか設定していませんが、font-weight: boldを指定すれば太字にすることもできますし、そのほかの設定もできます。

BloggerへのCSS追加手順

Bloggerへcode-prettifyの見た目を設定するCSSを追加するには下記の手順で行います。

Bloggerの設定画面で、

  1. [テーマ]の編集画面を表示
  2. [カスタマイズ]ボタンを押下
  3. Blogger テーマ デザイナーを表示
  4. [上級者向け]ー[CSSを追加]ー[カスタム CSS を追加]のテキストボックスにCSSを追加
  5. [ブログに適用]ボタンを押下

他の選択肢

Bloggerでソースコードの色分け表示を行えるのは、code-prettifyだけではありません。

他の有力な選択肢としては、SyntaxHighlighterがあります。
SyntaxHighlighter

SyntaxHighlighterにはcode-prettifyにはない、行の強調表示の機能などがあります。

記事終わり

2017年10月28日土曜日

HTMLの見出しタグに連番を振るCSSの書き方

このブログで行っているHTMLの見出しタグ<h4>、<h5>、<h6>に連番を振るCSSの書き方をご紹介します。

このブログの見出しタグ周りのCSS

このブログのHTMLは、下記のように<h4>、<h5>、<h6>タグにクラス名を付与しています。

<h4 class="foacs-chapter">
<h5 class="foacs-section">
<h6 class="foacs-paragraph">

このブログの見出しタグ周りのCSSは下記のとおりです。

/*
見出し設定
class="foacs-chapter"
class="foacs-section"
class="foacs-paragraph"
*/
.foacs-chapter
{
    border-left: 0.5em solid var(--foacs-link-color);
    border-bottom: 1px solid var(--foacs-link-color);
    font-size: x-large;
    margin-top: 4em;
    margin-bottom: 1em;
    padding: 0.5em;
    counter-increment: --foacs-chapter-counter;
    counter-reset: --foacs-section-counter;
}

.foacs-chapter::before
{
    content: counter(--foacs-chapter-counter) ".";
    padding-right: 0.5em;
}

.foacs-section
{
    border-left: 0.5em solid var(--foacs-link-color);
    border-bottom: 1px solid var(--foacs-link-color);
    font-size: large;
    margin-top: 4em;
    margin-bottom: 1em;
    padding: 0.5em;
    counter-increment: --foacs-section-counter;
    counter-reset: --foacs-paragraph-counter;
}

.foacs-section::before
{
    content: counter(--foacs-chapter-counter) "." counter(--foacs-section-counter) ".";
    padding-right: 0.5em;
}

.foacs-paragraph
{
    border-left: 0.5em solid var(--foacs-link-color);
    border-bottom: 1px solid var(--foacs-link-color);
    font-size: medium;
    margin-top: 4em;
    margin-bottom: 1em;
    padding: 0.5em;
    counter-increment: --foacs-paragraph-counter;
}

.foacs-paragraph::before
{
    content: counter(--foacs-chapter-counter) "." counter(--foacs-section-counter) "." counter(--foacs-paragraph-counter) ".";
    padding-right: 0.5em;
}

このブログのCSSの説明

見出しタグに連番を振るための手順は下記のとおりです。

  1. HTMLの見出しタグ<h4>、<h5>、<h6>にCSSで連番を振るためのクラス名を付与する
  2. CSSの変数を作り、現在の見出しのCSS変数の値を1増やして、下位の見出しのCSS変数を0にする
  3. CSSの変数から値を取り出して、HTMLの見出しの前に表示する

これらの手順について説明します。

HTMLのクラス名

このブログではHTMLの見出しタグ<h4>、<h5>、<h6>に下記のようにクラス名を付与しています。

<h4 class="foacs-chapter">
<h5 class="foacs-section">
<h6 class="foacs-paragraph">

「foacs」はこのブログの英語名の単語の頭文字をつなげたもので、Bloggerで元から使用されている他のクラス名と重複しないように使用している接頭辞です。

クラス名 foacs-chapter、foacs-section、foacs-paragraphを付与したHTMLの見出しタグ<h4>、<h5>、<h6>にCSSの機能で連番を振っています。

CSS変数

HTMLの見出しタグに連番を振るためにCSSの変数を使用しています。 どのように変数を使って連番を振っているのか、<h4>タグの場合に絞ってご説明します。

連番の準備

<h4>タグに付与するクラスfoacs-chapterの装飾を指定している個所をご覧ください。

.foacs-chapter
{
    border-left: 0.5em solid var(--foacs-link-color);
    border-bottom: 1px solid var(--foacs-link-color);
    font-size: x-large;
    margin-top: 4em;
    margin-bottom: 1em;
    padding: 0.5em;
    counter-increment: --foacs-chapter-counter;
    counter-reset: --foacs-section-counter;
}

counter-incrementでCSS変数--foacs-chapter-counterを1増やしています。
counter-resetで--foacs-section-counterを0にしています。
CSS変数の初期値は0ですので、<h4 class="foacs-chapter">タグが最初に出現した時点で、変数--foacs-chapter-counterは1に、--foacs-section-counterは0になります。

CSS変数は宣言なし、型指定なしでいきなり使えます。 変数の最初の2つのハイフン「--」は、CSSでは変数名を2つのハイフンで始めましょうというお約束になっているので、それに従っています。 変数名として分かりにくいとか違和感があるというのであれば、最初の2つのハイフンはなくても問題ありません。

このブログのCSSでは下記の3種類の変数を使用して、HTMLの見出しタグに連番を振っています。

--foacs-chapter-counter
--foacs-section-counter
--foacs-paragraph-counter
連番の表示

CSS変数の値の準備ができたので、次にその値を表示します。 値の表示はクラスfoacs-chapterの擬似要素beforeを指定している個所をご覧ください。

.foacs-chapter::before
{
    content: counter(--foacs-chapter-counter) ".";
    padding-right: 0.5em;
}

<h4 class="foacs-chapter">タグの前にCSS変数の値を表示するために、擬似要素beforeを使用しています。

CSS変数の値は関数counterで取り出します。関数counterで取り出した値の後ろに文字列「. 」を追加しています。 CSSでこのように指定することで下記のHTMLは「1. 見出し」と表示されます。

<h4 class="foacs-chapter">見出し</h4>

クラスfoacs-chapterで<h4>タグに連番を振ったように、クラスfoacs-sectionで<h5>タグ、クラスfoacs-paragraphで<h6>タグに連番を振っています。

ちなみに、クラス名と疑似要素の間のコロン「:」が2つになっているのは、CSS3の規則に従っているからです。 CSS3では疑似クラスと区別するために疑似要素につけるコロンが2つになっています。

CSS変数の注意点

CSS変数を使用する際に注意したい点を説明します。

擬似要素before内ではcounter-incrementとcounter-resetは動作しない

擬似要素beforeを指定したセレクタ内では、counter-incrementとcounter-resetは動作しません。 下記の記述は動作しませんので注意してください。

/*
動作しない。
*/
.foacs-chapter::before
{
    counter-increment: --foacs-chapter-counter;
    counter-reset: --foacs-section-counter;
    content: counter(--foacs-chapter-counter) ". ";
    padding-right: 0.5em;
}
1つのセレクタ内で複数のcounter-incrementとcounter-resetは動作しない

1つのセレクタ内に複数のcounter-incrementを書いても最後のcounter-incrementしか動作しません。 counter-resetも同様です。

このブログでは下記のようなCSSは使っていませんが、ご参考までにご留意ください。 下記の記述では、counter-increment: --foacs-counter03のみが動作します。

/*
counter-increment: --foacs-counter01とcounter-increment: --foacs-counter02は動作しない。
counter-increment: --foacs-counter03のみが動作する。
*/
.foacs-li
{
    counter-increment: --foacs-counter01;
    counter-increment: --foacs-counter02;
    counter-increment: --foacs-counter03;
}

上記のように1つのセレクタ内で複数の変数を動作させたい場合は下記のように記述します。

/*
動作する。
変数は空白で区切る。
*/
.foacs-li
{
    counter-increment: --foacs-counter01 --foacs-counter02 --foacs-counter03;
}

変数は空白で区切ります。カンマ「,」では区切らないので注意してください。

BloggerへのCSSの追加

自分で作成したCSSをBloggerの自分のブログに適用するためには以下のようにします。

  1. [テーマ]の編集画面を表示
  2. [カスタマイズ]ボタンを押下
  3. Blogger テーマ デザイナーを表示
  4. [上級者向け]ー[CSSを追加]ー[カスタム CSS を追加]のテキストボックスにCSSをコピー&ペースト
  5. [ブログに適用]ボタンを押下

記事終わり