LoginSignup
8
11

More than 5 years have passed since last update.

パネル風のTableのtdエリア全体をaタグの有効範囲にする

Last updated at Posted at 2017-08-07

html/cssのTableのtdのエリア全体をaタグの有効範囲にしたかったので作業をメモ。

パネル風のTable

テーブルを作ります。デザインはフラットな感じにしました。
とりあえず、やりたいことは2つ。

1.Tableのtdのエリア全体をaタグの有効範囲にする。
2.パネル風(文字を中央に寄せる)にする。

スクリーンショット 2017-08-07 15.36.52.png

HTML
<table>
<tr>
<td><a href="http://#">eria1</a></td>
<td><a href="http://#">eria2</a></td>
<td><a href="http://#">eria3</a></td>
</tr>
</table>

CSS
table {
   table-layout: fixed;
   border-collapse: separate;
   border-spacing: 10px;
   width:100%;
}

table td {
   background-color: #ccc;
   width:150px;
   height:150px;
   font-size:14pt;
   text-align: center;
   vertical-align:middle;
}

table td a{
   color:#fff;
   text-decoration: none;
} 

エリア全体をaタグ有効範囲にする

display: block;
width: 100%;
height: 100%;

この三つをaタグに指定するってネット検索したら出てきたので、やってみました。

css
table td a{
    text-decoration: none;
    color:#fff;  

    display: block;
    width: 100%;
    height: 100%;
} 

スクリーンショット 2017-08-07 15.38.46.png

aタグは、エリア全体に広がったのですが、display:block; を使ったため、vertical-align:middle; を使えなくなってしまいました。そのため、文字が真ん中に揃っていない。

tdの微調整 Part.1

文字を真ん中に揃えるため、まずは line-height を使ってみました。tdの高さを指定します。

css
table td a{
    text-decoration: none;
    color:#fff;  
    display: block;
    width: 100%;
    height: 100%;

    line-height: 150px;
} 

aタグはエリア全体になって、文字が真ん中に揃った!

スクリーンショット 2017-08-07 15.36.52.png

けど、中の文字を二行にすると、広がってしまいます。line-heightだから、当然なんだけど・・・tdの中身が改行なしなら問題ないです。

スクリーンショット 2017-08-07 15.39.49.png

tdの微調整 Part.2 (文字が2行になっても対応)

css
table td a{
    text-decoration: none;
    color:#fff;      
    display: block;
    width: 100%;
    height: 100%;

    padding:50px 0;
} 

1行と2行だとずれてしまうけど、なんとか真ん中に寄せられる感じです。

スクリーンショット 2017-08-07 15.35.44.png

力技ではなく、調整できるといいのだけど。

追記 Part.3 これが一番かも

パネル風のListのliエリアをaタグの有効範囲にする」で、Listタグでも同じことができるか調査していたところ、発見!

table td a を幅を大きくするために、下記コードを記述。

margin: -75px;
padding: 75px 75px;

table td からはみ出した部分を表示しないように、下記コードを記述。

overflow: hidden;

css
table {
   table-layout: fixed;
   border-collapse: separate;
   border-spacing: 10px;
}

table td {
   background-color: #ccc;
   width:150px;
   height:150px;
   font-size:14pt;
   text-align: center;
   vertical-align:middle;
   overflow: hidden;
}

table td a{
   color:#fff;
   text-decoration: none;
   margin: -75px;
   padding: 75px 75px;
} 

table td a:hover{
   background-color:#aaa;
} 

カーソル当てると、tdエリア全体がaタグの有効範囲に!

スクリーンショット 2017-08-09 10.27.48.png

これで完成かな。

8
11
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
8
11