HTML/CSS {Article007}

説明文の表示 ライブデモを見る▶
ようこそ「HTML/CSS」へ...

HTMLのPRE, CODEタグ内に記述したソースコードに行番号を追加するには

CSS、JavaScript/jQuery、C#などのコードをWebフォーム(Webページ)に表示するときは、 HTMLの<pre><code>==ここにコードを記述する==</code></pre>を使用します。 しかし、JavaScriptやC#などのコードが長いときはコードの途中までしか表示されないといったことがあります。 このような場合、CSSを使用してコードをスクロールできるようにします。 ここでは、CSSを使用してコードをスクロールできるようにしたり、コードに行番号をつけるといった方法を解説します。 なお、コードに行番号を追加するサンプルではJavaScript/jQueryを使用しています。 図1をクリックすると拡大表示します。

click image to zoom!
図1

作成手順

  1. VS2019(Visual Studio 2019 or Visual Studio 2022)を起動したら新規のWebフォーム「Article007.aspx」を作成します。

  2. Webフォームのヘッダータグ内「<head>...</head>」にSTYLEタグを追加してsample1からsample5のCSSを入力します。
    
    Article007.aspx:
    
    <style>
        /*Reset defult CSS*/
        pre {
            max-width: 65em;
            overflow: hidden;
            background-color: #F0F0E8;
            border: none;
            border-left: none;
            border-left-width: 0px;
            display: normal;
            padding: 0px;
        }
            pre code b {
                color: black;
                font-weight: 400;
            }
                pre code b.green {
                    color: black;
                    font-weight: 400;
                }
                pre code b.blue {
                    color: black;
                    font-weight: 400;
                }
            pre.article007-sample1 {
                max-width: 65em;
                overflow: auto;
                background-color: #F0F0E8;
            }
            pre.article007-sample2 {
                max-width: 65em;
                overflow: auto;
                background-color: #F0F0E8;
                border: 1px solid #999;
                padding: 5px;
            }
            pre.article007-sample3 {
                max-width: 65em;
                overflow: auto;
                background-color: #F0F0E8;
                border: 1px solid #999;
                border-left-width: 8px;
                padding: 5px;
            }
            pre.article007-sample4 {
                max-width: 65em;
                overflow: auto;
                color: white;
                background-color: black;
                border: 1px solid #999;
                border-left-width: 8px;
                border-left-color: darkcyan;
                padding: 5px;
            }
                pre.article007-sample4 code b {
                    color: red;
                    font-weight: 400;
                }
                    pre.article007-sample4 code b.green {
                        color: darkseagreen;
                        font-weight: 400;
                    }
                    pre.article007-sample4 code b.blue {
                        color: blueviolet;
                        font-weight: 600;
                    }
            pre.article007-sample5 {
                max-width: 65em;
                overflow: auto;
                color: white;
                background-color: black;
                border: 1px solid #999;
                border-left-width: 8px;
                border-left-color: darkcyan;
                margin: 0 0 1em;
                padding: .5em 1em;
            }
    
                pre.article007-sample5 code, pre.article007-sample5 .line-number {
                    color: white; /* color of code */
                    display: block;
                }
                pre.article007-sample5 .line-number {
                    float: left;
                    margin: 0 1em 0 -1em;
                    border-right: 1px solid;
                    border-right-color: white; /* Color of border | */
                    text-align: right;
                }
                    pre.article007-sample5 .line-number span {
                        display: block;
                        color: coral; /* Color of Line Number 1,2,3,... */
                        padding: 0 .5em 0 1em;
                    }
                pre.article007-sample5 .cl {
                    display: block;
                    clear: both;
                }
                pre.article007-sample5 code b {
                    color: red;
                    font-weight: 400;
                }
                    pre.article007-sample5 code b.green {
                        color: lightcoral;
                        font-weight: 600;
                    }
                    pre.article007-sample5 code b.blue {
                        color: aquamarine;
                        font-weight: 500;
                    }
    </style>
    
  3. Webフォームのヘッダータグ内「<head>...</head>」にSCRIPTタグを追加してjQueryの最新ライブラリーを取り込みます。 ここではjQuery 3.6.0のライブラリーを取り込んでいます。 さらにSCRIPTタグを追加して、次のようなJavaScript/jQueryのコードを入力します。
    
    Article007.arpx:
    
    <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>
    <script type="text/javascript">
        // jQuery Document Ready Event...
        $(function () {
    
            $('input#btnApplyCss1').click(function () {
                $('pre#article007-sample1').toggleClass('article007-sample1');  
            });
    
            $('input#btnApplyCss2').click(function () {
                $('pre#article007-sample2').toggleClass('article007-sample2');
            });
    
            $('input#btnApplyCss3').click(function () {
                $('pre#article007-sample3').toggleClass('article007-sample3');
            });
    
            $('input#btnApplyCss4').click(function () {
                $('pre#article007-sample4').toggleClass('article007-sample4');
            });
    
            $('input#btnApplyCss5').click(function () {
                $('pre.article007-sample5-addline').each(function (index, element) {
                    var spanx = $(element).find('span.line-number');
                    if (spanx.length == 0) {
                        element.innerHTML = '<span class="line-number"></span>' + element.innerHTML + '<span class="cl"></span>';
                        var num = element.innerHTML.split(/\n/).length;
                        for (var j = 0; j < num; j++) {
                            var span = $(element).find('span.line-number');
                            span[0].innerHTML += '<span>' + (j + 1) + '</span>';
                        }            
                        $('pre.article007-sample5-addline').addClass('article007-sample5');
                    }
                    else {
                        $(spanx).remove();
                        $('pre.article007-sample5-addline').removeClass('article007-sample5');
                    }
                });
            });            
    
        });
    </script>
    
  4. Webフォームに「Sample #1」から「Sample #5」を入力します。
    
    Article007.aspx:
    
    <h3>Sample #1 (max-width: 65em; overflow: auto; background-color: #F0F0E8;)</h3>
    <input id="btnApplyCss1" type="button" style="background-color:orange" value="Apply CSS1 ! (Toggle Button)" />
    <pre id="article007-sample1">
    <code>
    protected void Page_Load(object sender, EventArgs e)
    {
        wc = WebConfig.GetWebConfig();
        pv = PublicVariable.GetPublicVarialbe(bolDebugMode: false, bolTraceMode: false, lblMessage: lblMessage, lblTrace: lblMessage);
        Session[ssPublicVariableObject] = pv;
        lblMessage.Text = "";
    
        if (!IsPostBack)
        {
            appName.InnerText = wc.strAppName;                                                  <b class="green">// Home, Liberal Arts,...</b>
            appType.InnerText = String.Format("{0}({1})", wc.strAppType, wc.strAppVersion);     <b class="green">// PROD(V1.0.0) or DEVL(V1.0.0)</b>
            appSub.InnerText = wc.strPoweredBy;                                                 <b class="green">// Powered by ASP.NET 4.x</b>
    
            lblDate.Text = String.Format("{0:yyyy/MM/dd}", DateTime.UtcNow.AddHours(9));
            lblTime.Text = String.Format("{0:HH:mm:ss}", DateTime.UtcNow.AddHours(9));
    
            copyRight.InnerHtml = wc.strCopyRight;
    
            AppLayer.Stats.UpdateViewCount(pv, "Root_Menu_HtmlCss_Article_Article007.aspx");
        }
    }  
    </code>
    </pre>
    
    <h3>Sample #2 (border:1px solid #999; padding: 5px;)</h3>
    <input id="btnApplyCss2" type="button" style="background-color:orange" value="Apply CSS2 ! (Toggle Button)" />
    <pre id="article007-sample2">
    <code>
    protected void Page_Load(object sender, EventArgs e)
    {
        wc = WebConfig.GetWebConfig();
        pv = PublicVariable.GetPublicVarialbe(bolDebugMode: false, bolTraceMode: false, lblMessage: lblMessage, lblTrace: lblMessage);
        Session[ssPublicVariableObject] = pv;
        lblMessage.Text = "";
    
        if (!IsPostBack)
        {
            appName.InnerText = wc.strAppName;                                                  <b class="green">// Home, Liberal Arts,...</b>
            appType.InnerText = String.Format("{0}({1})", wc.strAppType, wc.strAppVersion);     <b class="green">// PROD(V1.0.0) or DEVL(V1.0.0)</b>
            appSub.InnerText = wc.strPoweredBy;                                                 <b class="green">// Powered by ASP.NET 4.x</b>
    
            lblDate.Text = String.Format("{0:yyyy/MM/dd}", DateTime.UtcNow.AddHours(9));
            lblTime.Text = String.Format("{0:HH:mm:ss}", DateTime.UtcNow.AddHours(9));
    
            copyRight.InnerHtml = wc.strCopyRight;
    
            AppLayer.Stats.UpdateViewCount(pv, "Root_Menu_HtmlCss_Article_Article007.aspx");
        }
    }  
    </code>
    </pre>
    
    <h3>Sample #3 (border-left-width: 10px;)</h3>
    <input id="btnApplyCss3" type="button" style="background-color:orange" value="Apply CSS3 ! (Toggle Button)" />
    <pre id="article007-sample3">
    <code>
    protected void Page_Load(object sender, EventArgs e)
    {
        wc = WebConfig.GetWebConfig();
        pv = PublicVariable.GetPublicVarialbe(bolDebugMode: false, bolTraceMode: false, lblMessage: lblMessage, lblTrace: lblMessage);
        Session[ssPublicVariableObject] = pv;
        lblMessage.Text = "";
    
        if (!IsPostBack)
        {
            appName.InnerText = wc.strAppName;                                                  <b class="green">// Home, Liberal Arts,...</b>
            appType.InnerText = String.Format("{0}({1})", wc.strAppType, wc.strAppVersion);     <b class="green">// PROD(V1.0.0) or DEVL(V1.0.0)</b>
            appSub.InnerText = wc.strPoweredBy;                                                 <b class="green">// Powered by ASP.NET 4.x</b>
    
            lblDate.Text = String.Format("{0:yyyy/MM/dd}", DateTime.UtcNow.AddHours(9));
            lblTime.Text = String.Format("{0:HH:mm:ss}", DateTime.UtcNow.AddHours(9));
    
            copyRight.InnerHtml = wc.strCopyRight;
    
            AppLayer.Stats.UpdateViewCount(pv, "Root_Menu_HtmlCss_Article_Article007.aspx");
        }
    }  
    </code>
    </pre>
    
    <h3>Sample #4 (color:white; background-color: black; border-left-color: darkcyan;)</h3>
    <input id="btnApplyCss4" type="button" style="background-color:orange" value="Apply CSS4 ! (Toggle Button)" />
    <pre id="article007-sample4">
    <code>
    protected void Page_Load(object sender, EventArgs e)
    {
        wc = WebConfig.GetWebConfig();
        pv = PublicVariable.GetPublicVarialbe(bolDebugMode: false, bolTraceMode: false, lblMessage: lblMessage, lblTrace: lblMessage);
        Session[ssPublicVariableObject] = pv;
        lblMessage.Text = "";
    
        if (!IsPostBack)
        {
            appName.InnerText = wc.strAppName;                                                  <b class="green">// Home, Liberal Arts,...</b>
            appType.InnerText = String.Format("{0}({1})", wc.strAppType, wc.strAppVersion);     <b class="green">// PROD(V1.0.0) or DEVL(V1.0.0)</b>
            appSub.InnerText = wc.strPoweredBy;                                                 <b class="green">// Powered by ASP.NET 4.x</b>
    
            lblDate.Text = String.Format("{0:yyyy/MM/dd}", DateTime.UtcNow.AddHours(9));
            lblTime.Text = String.Format("{0:HH:mm:ss}", DateTime.UtcNow.AddHours(9));
    
            copyRight.InnerHtml = wc.strCopyRight;
    
            AppLayer.Stats.UpdateViewCount(pv, "Root_Menu_HtmlCss_Article_Article007.aspx");
        }
    }  
    </code>
    </pre>
    
    <h3>Sample #5 (add line number; CSS+jQuery)</h3>
    <input id="btnApplyCss5" type="button" style="background-color:orange" value="Apply CSS5 ! (Toggle Button)" />
    <br /><br />
    <pre id="article007-sample5-1" class="article007-sample5-addline"><code>protected void Page_Load(object sender, EventArgs e)
    {
        wc = WebConfig.GetWebConfig();
        pv = PublicVariable.GetPublicVarialbe(bolDebugMode: false, bolTraceMode: false, lblMessage: lblMessage, lblTrace: lblMessage);
        Session[ssPublicVariableObject] = pv;
        lblMessage.Text = "";
    
        if (!IsPostBack)
        {
            appName.InnerText = wc.strAppName;                                                  <b class="green">// Home, Liberal Arts,...</b>
            appType.InnerText = String.Format("{0}({1})", wc.strAppType, wc.strAppVersion);     <b class="green">// PROD(V1.0.0) or DEVL(V1.0.0)</b>
            appSub.InnerText = wc.strPoweredBy;                                                 <b class="green">// Powered by ASP.NET 4.x</b>
    
            lblDate.Text = String.Format("{0:yyyy/MM/dd}", DateTime.UtcNow.AddHours(9));
            lblTime.Text = String.Format("{0:HH:mm:ss}", DateTime.UtcNow.AddHours(9));
    
            copyRight.InnerHtml = wc.strCopyRight;
    
            AppLayer.Stats.UpdateViewCount(pv, "Root_Menu_HtmlCss_Article_Article007.aspx");
        }
    }</code></pre>
    
    <pre id="article007-sample5-2" class="article007-sample5-addline"><code><b class="green">pre</b> {
        <b class="blue">max-width</b>: <b class="red">65em</b>;
        <b class="blue">overflow</b>: <b class="red">hidden</b>;
        <b class="blue">background-color</b>: <b class="red">#F0F0E8</b>;
        <b class="blue">border</b>: <b class="red">none</b>;
        <b class="blue">border-left</b>: <b class="red">none</b>;
        <b class="blue">border-left-width</b>: <b class="red">0px</b>;
        <b class="blue">display</b>: <b class="red">normal</b>;
        <b class="blue">padding</b>: <b class="red">0px</b>;
    }</code></pre>
    

操作手順と解説

  1. サンプルが表示されたらボタン[Apply CSS1 (Toggle Button)]をクリックします。 サンプルのコードがCSSでフォーマットされて表示されます。再度ボタンをクリックするとフォーマットされない状態に戻ります。

  2. 同様の手順で[Apply CCS2]から[Apply CSS5]のボタンをクリックしてみてください。

  3. click image to zoom!
    図2:
    [Apply CSS5]ボタンをクリックしたときは、サンプルのコードに行番号が追加されて表示されます。 コードの行番号はJavaScript/jQueryを使用して表示しています。 WindowsのGoogle Chromeを使用しているときは[F12]を押してデバッグツールを表示して[Elements]タブをクリックすると、 JavaScript/jQueryで追加した行番号が表示されます。JavaScript/jQueryでは親要素「<span class="line-number"></span>」を追加して、 この親要素に行番号を表示する子要素の「<span>1</span><span>2</span><span>3</span>...」を追加しています。 図2の画像をクリックすると図が拡大表示されます。 図2の下に表示されている図のキャプション【図2】上にマウスを移動すると図の説明が表示されます。

  4. span要素内に配置した行番号をコードの左端に表示させるには6行目の「float: left」を追加します。 サンプルコードの色(white)は2行目、行番号とコードの境界線の色(white)は9行目、行番号の色(coral)は14行目で指定しています。
    pre.article007-sample5 code, pre.article007-sample5 .line-number {
        color: white; /* Color of code */
    }
    
    pre.article007-sample5 .line-number {
        float: left;
        margin: 0 1em 0 -1em;
        border-right: 1px solid;
        border-right-color: white; /* Color of border | */
        text-align: right;
    }
    
        pre.article007-sample5 .line-number span {
            color: coral; /* Color of Line Number 1,2,3,... */
            padding: 0 .5em 0 1em;
        }
    
    pre.article007-sample5 .cl {
        clear: both;
    }

Live DEMO

Sample #1 (max-width: 65em; overflow: auto; background-color: #F0F0E8;)

protected void Page_Load(object sender, EventArgs e)
{
    wc = WebConfig.GetWebConfig();
    pv = PublicVariable.GetPublicVarialbe(bolDebugMode: false, bolTraceMode: false, lblMessage: lblMessage, lblTrace: lblMessage);
    Session[ssPublicVariableObject] = pv;
    lblMessage.Text = "";

    if (!IsPostBack)
    {
        appName.InnerText = wc.strAppName;                                                  // Home, Liberal Arts,...
        appType.InnerText = String.Format("{0}({1})", wc.strAppType, wc.strAppVersion);     // PROD(V1.0.0) or DEVL(V1.0.0)
        appSub.InnerText = wc.strPoweredBy;                                                 // Powered by ASP.NET 4.x

        lblDate.Text = String.Format("{0:yyyy/MM/dd}", DateTime.UtcNow.AddHours(9));
        lblTime.Text = String.Format("{0:HH:mm:ss}", DateTime.UtcNow.AddHours(9));

        copyRight.InnerHtml = wc.strCopyRight;

        AppLayer.Stats.UpdateViewCount(pv, "Root_Menu_HtmlCss_Article_Article007.aspx");
    }
}  

Sample #2 (border:1px solid #999; padding: 5px;)

protected void Page_Load(object sender, EventArgs e)
{
    wc = WebConfig.GetWebConfig();
    pv = PublicVariable.GetPublicVarialbe(bolDebugMode: false, bolTraceMode: false, lblMessage: lblMessage, lblTrace: lblMessage);
    Session[ssPublicVariableObject] = pv;
    lblMessage.Text = "";

    if (!IsPostBack)
    {
        appName.InnerText = wc.strAppName;                                                  // Home, Liberal Arts,...
        appType.InnerText = String.Format("{0}({1})", wc.strAppType, wc.strAppVersion);     // PROD(V1.0.0) or DEVL(V1.0.0)
        appSub.InnerText = wc.strPoweredBy;                                                 // Powered by ASP.NET 4.x

        lblDate.Text = String.Format("{0:yyyy/MM/dd}", DateTime.UtcNow.AddHours(9));
        lblTime.Text = String.Format("{0:HH:mm:ss}", DateTime.UtcNow.AddHours(9));

        copyRight.InnerHtml = wc.strCopyRight;

        AppLayer.Stats.UpdateViewCount(pv, "Root_Menu_HtmlCss_Article_Article007.aspx");
    }
}  

Sample #3 (border-left-width: 10px;)

protected void Page_Load(object sender, EventArgs e)
{
    wc = WebConfig.GetWebConfig();
    pv = PublicVariable.GetPublicVarialbe(bolDebugMode: false, bolTraceMode: false, lblMessage: lblMessage, lblTrace: lblMessage);
    Session[ssPublicVariableObject] = pv;
    lblMessage.Text = "";

    if (!IsPostBack)
    {
        appName.InnerText = wc.strAppName;                                                  // Home, Liberal Arts,...
        appType.InnerText = String.Format("{0}({1})", wc.strAppType, wc.strAppVersion);     // PROD(V1.0.0) or DEVL(V1.0.0)
        appSub.InnerText = wc.strPoweredBy;                                                 // Powered by ASP.NET 4.x

        lblDate.Text = String.Format("{0:yyyy/MM/dd}", DateTime.UtcNow.AddHours(9));
        lblTime.Text = String.Format("{0:HH:mm:ss}", DateTime.UtcNow.AddHours(9));

        copyRight.InnerHtml = wc.strCopyRight;

        AppLayer.Stats.UpdateViewCount(pv, "Root_Menu_HtmlCss_Article_Article007.aspx");
    }
}  

Sample #4 (color:white; background-color: black; border-left-color: darkcyan;)

protected void Page_Load(object sender, EventArgs e)
{
    wc = WebConfig.GetWebConfig();
    pv = PublicVariable.GetPublicVarialbe(bolDebugMode: false, bolTraceMode: false, lblMessage: lblMessage, lblTrace: lblMessage);
    Session[ssPublicVariableObject] = pv;
    lblMessage.Text = "";

    if (!IsPostBack)
    {
        appName.InnerText = wc.strAppName;                                                  // Home, Liberal Arts,...
        appType.InnerText = String.Format("{0}({1})", wc.strAppType, wc.strAppVersion);     // PROD(V1.0.0) or DEVL(V1.0.0)
        appSub.InnerText = wc.strPoweredBy;                                                 // Powered by ASP.NET 4.x

        lblDate.Text = String.Format("{0:yyyy/MM/dd}", DateTime.UtcNow.AddHours(9));
        lblTime.Text = String.Format("{0:HH:mm:ss}", DateTime.UtcNow.AddHours(9));

        copyRight.InnerHtml = wc.strCopyRight;

        AppLayer.Stats.UpdateViewCount(pv, "Root_Menu_HtmlCss_Article_Article007.aspx");
    }
}  

Sample #5 (add line number; CSS+jQuery)


protected void Page_Load(object sender, EventArgs e)
{
    wc = WebConfig.GetWebConfig();
    pv = PublicVariable.GetPublicVarialbe(bolDebugMode: false, bolTraceMode: false, lblMessage: lblMessage, lblTrace: lblMessage);
    Session[ssPublicVariableObject] = pv;
    lblMessage.Text = "";

    if (!IsPostBack)
    {
        appName.InnerText = wc.strAppName;                                                  // Home, Liberal Arts,...
        appType.InnerText = String.Format("{0}({1})", wc.strAppType, wc.strAppVersion);     // PROD(V1.0.0) or DEVL(V1.0.0)
        appSub.InnerText = wc.strPoweredBy;                                                 // Powered by ASP.NET 4.x

        lblDate.Text = String.Format("{0:yyyy/MM/dd}", DateTime.UtcNow.AddHours(9));
        lblTime.Text = String.Format("{0:HH:mm:ss}", DateTime.UtcNow.AddHours(9));

        copyRight.InnerHtml = wc.strCopyRight;

        AppLayer.Stats.UpdateViewCount(pv, "Root_Menu_HtmlCss_Article_Article007.aspx");
    }
}
pre {
    max-width: 65em;
    overflow: hidden;
    background-color: #F0F0E8;
    border: none;
    border-left: none;
    border-left-width: 0px;
    display: normal;
    padding: 0px;
}