LoginSignup
3
1

More than 3 years have passed since last update.

左に画像があって、真ん中にタイトルと説明があって、右に日付があるようなカードのHTML/CSSでの表現はGridが便利だった

Last updated at Posted at 2019-10-04

こういうのHTML/CSSで書く時どうしてます?

image.png

最低限必要な中身はこんな感じだと思います

<div class="class">
  <img class="image" />
  <h2 class="title" />
  <p class="description" />
  <p class="date" />
</div>

Twitterでも聞いてみました

なんとなく思いつくのは display: flexじゃないですかね。

ただその場合 h2.titlep.descriptionを更に<div/>で囲ってあげる必要がありますね。それでも問題ないんですが、どうせならHTMLはこのままで、CSSのみでデザインを反映したくないですか?

Twitter最高。display: grid使えばいい感じにできそうということが模範解答つきで教えてもらえました。神かよ..:pray:

更にこのあたりを参考にして、実装してみました。

※gridに関する記述のみ抜粋

.card {
  display: grid;
  row-gap: 8px;
  column-gap: 16px;
  grid-template:
    "image title date" 30px
    "image description description" 1fr /
    80px 1fr 90px;
}

.image {
  grid-area: image;  
}

.title {
  grid-area: title;  
}

.description {
  grid-area: description;
}

.date {
  grid-area: date;
}

grid-templateの箇所だけ、最初は吐き気を催すかもしれませんが、落ち着いてください。何度みても吐き気がします。

なんとなくテーブルのような構造をイメージしながら読めばわかりやすいのかな、と個人的に思っているのですが

grid-template:
    /* 1行目の高さ(row)と、1行目に含む内容 */
    "image title date" 30px

    /* 2行目の高さ(row ※1frは残りの長さを指定するgridでの表現)と、2行目に含む内容
       スラッシュ(/)以降は、縦の列(column)の幅をそれぞれ指定
     */
    "image description description" 1fr /
    80px 1fr 90px;
}

まあこんな感じです、、。まあ雰囲気で使っていきましょう、、

結果がこちら〜

See the Pen Grid Card by Kobashi syunsuke (@ksyunnnn) on CodePen.

それでは、Happy Gridライフを〜:wave:

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1