2カラムと3カラムをHTMLの書き方で変える方法を考えています。
<div class="container two-column">
<div class="main">メイン</div>
<div class="side">サイド</div>
</div>
.
<div class="container three-column">
<div class="main">メイン</div>
<div class="side">サイド</div>
<div class="side">サイド</div>
</div>
.
一番簡単なのはこのように囲っている親要素にクラスを追加する事(two-columnとかthree-columnとか)だと思いますが、クラスを追加せずに、子要素の数(mainとsideだけなら2カラム用のスタイルを適用し、mainとside2つなら3カラム用のスタイルを適用)で変更する事は出来ないでしょうか?
みんなの回答 4 件
sideの幅が決まってるならcontainerにdisplay:table;table-layout:fixed;、
mainとsideをdisplay:table-cell、sideにwidth指定だといけそうだけど
3カラムのときにsideの幅が変わるならlast-childとfirst-childを上手く活用するか
できません
クラスを手動で付けるか、jqueryで付けなさい
できるよ。
現在は拡張性を得るためにマルチクラスを使うのが主流だけど、一方では拡張性が必要のないケースもあるわけで、究極的には一切クラスを使わずに書くこともできるよ。cssがトリッキーになる分、htmlが恐ろしくシンプルになるね。
<style>
/*共通*/
main > article{
width: 100px;
height: 100px;
margin: 10px;
border: 1px solid #000;
}
/*シングルカラム*/
main > article:only-child{
background: #f00;
}
/*2カラム*/
main > article:first-child:nth-last-child(2),
main > article:first-child:nth-last-child(2) ~ article{
background: #00f;
}
/*3カラム*/
main > article:first-child:nth-last-child(3),
main > article:first-child:nth-last-child(3) ~ article{
background: #0f0;
}
</style>
<main>
<article>A</article>
<article>B</article>
<article>C</article>
</main>
これでいい?
.main,.side{
float: left;
border: 1px solid #333;
box-sizing:border-box;
}
.main{
width:60%;
}
.side{
width:40%;
}
.side:nth-last-of-type(2),
.side:nth-of-type(3){
width:20%;
}
関連するトピックス