【初級編】CSSを書くときに徹底している事


表題の件をまとめ。

1. style= は死んでも書かない。

 ①可読性を殺す
 ②重複だらけでみっともない
 ③子要素や妹要素に影響を与えない

 可読性の要らない極小のDHTMLで、今後絶対に修正しない箇所でもない限り、欠点だらけの style= は書かない。(で、そんなDHTMLを公開する事はない。)
 「取り急ぎ」で用いたとしても十中八九、後で class= などに書き換えるのだから、最初から class= を使う。

2. id= は極力減らす。

 idの割り振りは、javascriptで getElementById を適用する用途に限る。
 jsで呼び出さない限り id= は使わず、 class= で代替する。

<style>#hoge,#fuga{width:100%;}</style>

 ↑のような書き方も↓のように早めに修正しておく。

<style>.hoge{width:100%;}</style>
<.. id=hoge class=hoge><.. id=fuga class=hoge> 

3. class= も極力減らす。

 例えば↓こんな書き方は非常に馬鹿馬鹿しい。ファイルサイズの面でも、メンテナンス性も最悪。5個目に新しい li を割り込ませたら6,7..30個目も全部書き直すの???

<style>li.a{color:#300;}li.b{color:#003;}</style>
<ul>
<li class=a><li class=b><li class=a><li class=b>...
</ul>

 最初からこうしておく↓

<style>
.aorb>*{color:#003;}.aorb>*:nth-of-type(2n){color:#300;}
</style>
<ul class=aorb>
<li><li><li><li>...
</ul>

 アンチflexbox(..あんなメンヘラに振り回されたくないよね。)勢にはこんなやり方も。↓

<style>
li{float:left;}
.w25,.w25+li,.w25+li+li,.w25+li+li+li{width:25%;}
.w50,.w50+li{width:50%;}
.w100{width:100%;}
</style>
<ul>
<li class=w50>50<li>50
<li class=w25>25<li>25<li>25<li>25
<li class=w25>25<li>25<li>25<li>25
<li class=w25>25<li>25<li>25<li>25
<li class=w100>100
</ul>

4. 要素ではなく属性値をベースにする。

<style>
.c1001{position:absolute;top:0;left:0;width:50%;height:30%;}
.c1002{position:absolute;top:30%;left:0;width:50%;height:70%;}
.c1003{position:absolute;top:0;left:50%;width:50%;height:30%;}
.c1004{position:absolute;top:30%;left:50%;width:50%;height:70%;}
</style>

 半年ぶりに読んで全容を把握し易いのは、↑前者より↓後者。

<style>
/*rule*/body>*{position:absolute;}
/*y*/.c1001,.c1003{top:0;height:30%;}.c1002,.c1004{top:30%;height:70%;}
/*x*/body>*{width:50%;}.c1001,.c1002{left:0;}.c1003,.c1004{left:50%;}
</style>

5. 予め数値化しておく。

 日々、頻繁に書いている属性値は数値クラスで管理して毎回コピペが便利。
 その属性値を当てたいタグネームやID、亜種クラスも、.c**の右に足して行き、公開前に要らない行だけ削除。

*{margin:0;padding:0;box-sizing:border-box;
font-family:'Meiryo';transition:.7s;
scroll-behavior:smooth;}
ul{list-style:none;}i{font-style:normal;}
a,u,s{text-decoration:none;}

.c10{display:none;}
.c11{display:block;}
.c12,b,i,u,s,li{display:block;float:left;}
.c13{display:inline-block;}
.c14{opacity:0;pointer-events:none;}
.c15{position:fixed;}
.c16{position:absolute;}
.c17{position:sticky;}
.c18{position:relative;}
.c15,.c17,.c19{z-index:2;}
.c20{width:auto;}
.c21,.c35{width:100%;}
.c22{width:50%;}
.c23{width:33.33%;}
.c24{width:25%;}
.c25{width:20%;}
.c26{width:16.66%}
.c27{text-align:left;}
.c28{text-align:center;}
.c29{text-align:right;}
.c30{height:0;}
.c31{height:100%;}
.c32{height:auto;line-height:25px;}
.c33,.c34,.c35{height:30px;line-height:30px;}
.c34{width:30px;}
.c36{overflow:hidden;}
.c37{overflow:scroll;}
.c38{white-space:nowrap;overflow-x:scroll;overflow-y:hidden;}
.c39{overscroll-behavior:none;}