--- title: contain slug: Web/CSS/contain tags: - CSS - CSS Containment - CSS Property - Layout - NeedsExample - Paint - Reference - Style - Web - 'recipe:css-property' translation_of: Web/CSS/contain ---
contain は CSS のプロパティで、ある要素とその内容が、できる限り多く、文書ツリーの他の部分から独立していることを示します。これによってブラウザーがレイアウト、スタイル、描画、寸法、およびその組み合わせの再計算を、ページ全体ではなく DOM の限られた領域に対して行うことで、性能上の明らかな利点をもたらします。
このプロパティはページ上にそれぞれ独立したたくさんのウィジェットがあるときに有益であり、ウィジェットの内部を、ウィジェットの囲みボックスの外側の副作用から守るために使用することができます。
注: (paint, strict, content のいずれかの値で) 適用された場合、このプロパティは以下のものを生成します。
absolute または fixed の子孫)。/* キーワード値 */ contain: none; contain: strict; contain: content; contain: size; contain: layout; contain: style; contain: paint; /* 複数のキーワード */ contain: size paint; contain: size layout paint; /* グローバル値 */ contain: inherit; contain: initial; contain: unset;
contain プロパティは以下のうちの一つで指定します。
none, strict, content の何れかのキーワードを単独で使用。size, layout, style, and paint の各キーワードを1つ以上、任意の順序で使用。nonestrictstyle を除くすべての抑制規則がその要素に適用されることを示します。これは contain: size layout paint と同等です。contentsize および style 以外の抑制規則がその要素に適用されることを示します。これは contain: layout paint と同等です。sizelayoutstylepaint{{cssinfo}}
以下のマークアップは多数のコンテンツを持つ記事からなるものです。
<h1>My blog</h1> <article> <h2>Heading of a nice article</h2> <p>Content here.</p> </article> <article> <h2>Another heading of another article</h2> <img src="graphic.jpg" alt="photo"> <p>More content here.</p> </article>
それぞれの <article> および <img> には境界があり、画像は浮動状態です。
img {
float: left;
border: 3px solid black;
}
article {
border: 1px solid black;
}
{{EmbedLiveSample('Simple_layout', '100%', '300')}}
1つ目の記事の下部に別の画像を挿入すると、 DOM ツリーの大部分が再レイアウトされたり、再描画されたりする可能性があり、2つ目の記事のレイアウトにも支障をきたしてしまいます。
<h1>My blog</h1> <article> <h2>Heading of a nice article</h2> <p>Content here.</p> <img src="i-just-showed-up.jpg" alt="social"> </article> <article> <h2>Another heading of another article</h2> <img src="graphic.jpg" alt="photo"> <p>More content here.</p> </article>
img {
float: left;
border: 3px solid black;
}
article {
border: 1px solid black;
}
ご覧の通り、浮動要素の動作方法が原因で、最初の画像が2つ目の記事の領域内に掛かってしまっています。
{{EmbedLiveSample('Float_interference', '100%', '300')}}
それぞれの article の contain プロパティを content の値を設定することで、新しい要素が挿入されたときに、ブラウザーはそれが含まれる要素のサブツリーの再計算をするだけで、その外側には何もする必要がないことを理解します。
<h1>My blog</h1> <article> <h2>Heading of a nice article</h2> <p>Content here.</p> <img src="i-just-showed-up.jpg" alt="social"> </article> <article> <h2>Another heading of another article</h2> <img src="graphic.jpg" alt="photo"> <p>More content here.</p> </article>
img {
float: left;
border: 3px solid black;
}
article {
border: 1px solid black;
contain: content;
}
これで、最初の画像が2つ目の記事の下に浮いてくることなく、包含する要素の範囲内に留まることも意味します。
{{EmbedLiveSample('Fixing_with_contain', '100%', '330')}}
| 仕様書 | 状態 | 備考 |
|---|---|---|
| {{SpecName('CSS Containment')}} | {{Spec2('CSS Containment')}} | 初回定義 |
{{Compat("css.types.global_keywords.initial")}}