Menu
Coddy logo textTech

固定配置

CoddyのHTMLジャーニー「Styling with CSS」セクションの一部 — レッスン 58/76。

CSSにおいて、固定配置(fixed positioning)は、どれだけスクロールしても要素を画面上の同じ場所に保持します。position: fixed;を設定すると、その要素は通常のレイアウトから取り除かれるため、他の要素はそれを無視します。ブラウザのウィンドウに対して固定されたままになるため、常に表示させておきたいヘッダー、フッター、またはメニューに便利です。

固定配置(fixed positioning)を使用するための基本構文は以下の通りです:

selector {
    position: fixed;
    top: value;
    right: value;
    bottom: value;
    left: value;
}
  • position: fixed;: この宣言は、要素の配置方法を fixed に設定します。
  • top, right, bottom, left: これらのプロパティは、ビューポートに対する要素の位置を指定します。ピクセル(px)、em(em)、パーセンテージ(%)、またはその他の有効なCSS単位で指定された、正または負の値を使用できます。

例えば:

.header {
    position: fixed;
    top: 0;
    left: 0;
}

この例では、クラス header を持つ要素は、position: fixed;top: 0;、および left: 0; によってビューポートの上部に固定されます。 

challenge icon

チャレンジ

簡単

ヘッダー (<div>) と段落 (<p>) を含むHTMLドキュメントが与えられています。あなたのタスクは、固定配置(fixed positioning)を使用して、ページをスクロールしてもヘッダーがビューポートの上部に留まるようにすることです。以下の手順に従ってください。

  1. header クラスを持つ <div> 要素をターゲットにするCSSルールを記述します。
  2. .header 要素の position プロパティを fixed に設定します。
  3. .header 要素の top プロパティを 0 に、left プロパティを 0 に設定します。これにより、ヘッダーがビューポートの左上隅に配置されます。
  4. .header 要素の width プロパティを 100% に設定して、ビューポート全体に広がるようにします。
  5. .header 要素の background-color プロパティを #fcc726 (ゴールデンイエロー) に設定して、ページコンテンツに対して見えるようにします。
  6. 見た目を良くするために、text-align プロパティを center に設定します。

チートシート

固定配置(Fixed positioning)は、スクロールに関係なく、要素を画面上の同じ場所に保持します。その要素は通常のレイアウトフローから取り除かれます。

基本的な構文:

selector {
    position: fixed;
    top: value;
    right: value;
    bottom: value;
    left: value;
}

例 - 要素をビューポートの左上に固定する:

.header {
    position: fixed;
    top: 0;
    left: 0;
}

位置プロパティ(toprightbottomleft)は、ビューポートに対する要素の位置を指定し、ピクセル、em、パーセンテージ、またはその他のCSS単位の値を受け入れます。

自分で試してみよう

<html>
<head>
    <title>Fixed Positioning</title>
    <style>
        /* Write CSS rules here */
    </style>
</head>
<body>
    <div class="header">This is the header</div>
    <p>This is some content below the header. Scroll down to see the fixed positioning in action.</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
</body>
</html>
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Styling with CSSのすべてのレッスン