【備忘録:HTML/CSS】data属性はCSS設計で大事だよね?
data属性を活用していきたい
例えば、上記のようなボタンがあったとして、LP制作とかだと、
「そのボタンに合ったクラスを作成する」という感じになるかと思います。
hoge.html
<p><a href="#" class="m-btn-small">幅決まっているボタン</a></p>
<p><a href="#" class="m-btn">幅100%ボタン</a></p>
hoge.scss
.m-btn{
position: relative;
display: inline-block;
color: #fff;
background: pink;
font-size: 1.4rem;
font-weight: bold;
padding: 6px 20px;
width: 100%;
border-radius: 5px;
max-width: 100%;
text-align: center;
text-decoration: none;
&-small{
position: relative;
display: inline-block;
color: #fff;
background: pink;
font-size: 1.4rem;
font-weight: bold;
padding: 6px 20px;
width: 100%;
border-radius: 5px;
max-width: 400px;//ここだけ値を変更
text-align: center;
text-decoration: none;
}
}
この場合LPであればいいのですが、サイト運用やサイトリニューアルなどで、「ボタンの色を青に変更したい」とかなった場合を考えると、
hoge.scss
.m-btn{
position: relative;
display: inline-block;
color: #fff;
background: pink;
font-size: 1.4rem;
font-weight: bold;
padding: 6px 20px;
width: 100%;
border-radius: 5px;
max-width: 100%;
text-align: center;
text-decoration: none;
&-small{
position: relative;
display: inline-block;
color: #fff;
background: pink;
font-size: 1.4rem;
font-weight: bold;
padding: 6px 20px;
width: 100%;
border-radius: 5px;
max-width: 400px;//ここだけ値を変更
text-align: center;
text-decoration: none;
&-blue{
position: relative;
display: inline-block;
color: #fff;
background: blue;//ここの色を変えるために他のプロパティも記述しないといけない
font-size: 1.4rem;
font-weight: bold;
padding: 6px 20px;
width: 100%;
border-radius: 5px;
max-width: 400px;
text-align: center;
text-decoration: none;
}
}
}
上記のようになってしまい、
・ cssが冗長になってしまう
・ 冗長になった分保守が大変
・ 他の色や幅を追加したいときにさらに冗長になる
などデメリットが多くあります。
data属性を使った場合
hoge02.html
<p><a href="#" class="m-btn" data-btn-width="small">幅決まっているボタン</a></p>
<p><a href="#" class="m-btn">幅100%ボタン</a></p>
hoge02.scss
.m-btn{
position: relative;
display: inline-block;
color: #fff;
background: pink;
font-size: 1.4rem;
font-weight: bold;
padding: 6px 20px;
width: 100%;
border-radius: 5px;
max-width: 100%;
text-align: center;
text-decoration: none;
&[data-btn-width="small"]{
max-width: 400px;
}
}
このように.m-btnにdata属性を持たせ、それに対してcssを設定することで、
・ css記述が短縮できる
・ 保守がしやすい
・ 他の色や幅を追加しても分かりやすい
というメリットがあります。
先程の、「ボタンの色を青に変更したい」の場合でも、
hoge02.scss
.m-btn{
position: relative;
display: inline-block;
color: #fff;
background: pink;
font-size: 1.4rem;
font-weight: bold;
padding: 6px 20px;
width: 100%;
border-radius: 5px;
max-width: 100%;
text-align: center;
text-decoration: none;
&[data-btn-width="small"]{
max-width: 400px;
}
&[data-btn-bg="blue"]{
background: blue;
}
と記述が短くなり分かりやすいです。
まとめ
LPではなく、サイト運用、サイトリニューアルであれば、制作とその後の保守も考えdata属性を活用していくことをおすすめします。
Author And Source
この問題について(【備忘録:HTML/CSS】data属性はCSS設計で大事だよね?), 我々は、より多くの情報をここで見つけました https://qiita.com/hayahayahaya/items/f9bc5adc75b423e1b029著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .