アプリ版:「スタンプのみでお礼する」機能のリリースについて

<table>の<th><td>の幅を固定するのにCSSの:nth-childを使っていたのですが、
<colgroup>の<col>でも縦の幅を固定できると知り試してみました。
しかし、:nth-childを使った場合と<colgroup>を足した場合とで、幅が異なるようです。
添付画像のように、<colgroup>を使うと幅が狭くなりました。
(:nth-child を使うと幅が広くなる?)
このように幅が異なるのはどのような理由からでしょうか?

試したtest.htmは次の通りです。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>てすと</title>
<link rel="stylesheet" href="test.css">
</head>
<body>
<h1>テスト(colgroupあり)</h1>
<table>
<colgroup>
<col span="1" style="width:300px;">
<col span="1" style="width:70px;">
<col span="1" style="width:250px;">
<col span="10" style="width:62px;">
</colgroup>
<thead>
<tr>
<th>thead</th><th></th><th></th><th></th>
<th></th><th></th><th></th><th></th>
<th></th><th></th><th></th><th></th>
<th></th>
</tr>
</thead>
<tr>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
<td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
<td></td>
</tr>
</table>

</body>
</html>

test.cssは次の通りです。
@charset "UTF-8";

h1{height:50px;}
table{table-layout:fixed;}
table,tr{width:1240px;}
th,td{border:solid 5px black;text-align:center;height:100px;}
th{background-color:red;}
tr:nth-child(2n+1){background-color:blue;}
tr:nth-child(2n+0){background-color:white;}
th:nth-child(1),td:nth-child(1){width:300px;}
th:nth-child(2),td:nth-child(2){width:70px;}
th:nth-child(3),td:nth-child(3){width:250px;}
th:nth-child(n+4),td:nth-child(n+4){width:62px;}

よろしくお願いします。

「<table>の<td>の幅が:nth-」の質問画像

A 回答 (1件)

CSSボックスモデルにおいて td の幅は padding と border 込みで計算されます


td { width:300px; border-width:5px; padding:1px; }
ならば
幅 = 300 + 5*2 + 1*2 = 312px

col や colgroup には padding と border が無いので
col { width:300px; }
ならば
幅 = 300px

注意
table { border-collapse:collapse; } だとさらに計算がややこしくなります
    • good
    • 0
この回答へのお礼

test.cssを次のように変えたら同じになることを確認しました。
ありがとうございました。m(_ _)m

@charset "UTF-8";

h1{height:50px;}
table{table-layout:fixed;}
table,tr{width:1240px;}
th,td{height:100px;padding:0px;margin:0px;}
th{background-color:red;}
tr:nth-child(2n+1){background-color:blue;}
tr:nth-child(2n+0){background-color:white;}
th:nth-child(1),td:nth-child(1){width:300px;}
th:nth-child(2),td:nth-child(2){width:70px;}
th:nth-child(3),td:nth-child(3){width:250px;}
th:nth-child(n+4),td:nth-child(n+4){width:62px;}

お礼日時:2016/05/13 14:31

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!