WebSurfer's Home

トップ > Blog 1   |   ログイン
APMLフィルター

ブラウザ画面でセンタリング

by WebSurfer 2018年11月1日 12:10

CSS のみを使ってブラウザ画面上でコンテンツを上下左右センタリングする方法を、あまり需要はないとは思いますが、せっかく考えたので備忘録として書いておきます。

センタリング表示

上の画像は、width / height を 500px / 300px に設定した div 要素を、CSS の position プロパティを使って、ブラウザ画面の中央に来るようにしたものです。ブラウザの画面のサイズを変えても自動的に中央に来るようになっています。

CSS の設定は下にアップしたコードにありますので見てください。position を absolute とし、top / left を 50%(即ち画面の中央)に指定、margin に div 要素のサイズの半分をマイナス値で設定することにより div 要素が画面の中央に来るようにオフセットしています。

position プロパティの詳しい説明&デモは MDN web docs の記事「position」にありますので見てください。要点を抜粋すると以下の通りです。

An absolutely positioned element is an element whose computed position value is absolute or fixed. The top, right, bottom, and left properties specify offsets from the edges of the element's containing block. If the element has margins, they are added to the offset.

上の画像を表示したコードを以下にアップしておきます。ASP.NET Web Forms アプリの .aspx ページを使っていますが、ASP.NET は今回の記事には直接の関係はありません。(.html ページを使うとブラウザのキャッシュをいちいち消さなければならないのが面倒なので .aspx ページを使いました)

<%@ Page Language="C#" AutoEventWireup="true" 
    CodeFile="0049-Centering.aspx.cs" 
    Inherits="_0049_Centering" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Centering</title>
    <style type="text/css">
        body {
            background-color: #555;
        }

        .content {
            background-color: white;
            width:500px;
            height:300px;
            position:absolute;
            top:50%;
            left:50%;
            margin-left:-250px;
            margin-top:-150px;
            overflow:scroll;
        }
    </style>
</head>
<body>
  <form id="form1" runat="server">
    <div class="content">
      <h1>
        This page is horizontally / vertically centered on 
        screen that is wider than 500 / 300 pixels.
      </h1>
      <h2>
        Resize the browser window to see the effect.
      </h2>
      <p>
        An absolutely positioned element is an element 
        whose computed position value is absolute or fixed. 
        The top, right, bottom, and left properties specify 
        offsets from the edges of the element's containing 
        block. (The containing block is the ancestor 
        relative to which the element is positioned.) 
        If the element has margins, they are added to the 
        offset.
      </p>
    </div>
  </form>
</body>
</html>

Tags:

ASP.NET

About this blog

2010年5月にこのブログを立ち上げました。主に ASP.NET Web アプリ関係の記事です。

Calendar

<<  2018年11月  >>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

View posts in large calendar