2008.05.17
画像の大きさによって隣接ボックスの幅が可変する方法

テーブルの様に、画像の大きさによってコメントボックスの幅が伸縮します。widthとheightを指定しなくても画像の大きさを自動で取得しボックスの横幅を計算します。
確認済みのブラウザはIE6、IE7、firefox、opera、safari、Mac IE5です。
HTMLを次のように記述します。
HTMLコード
<!--[if lt IE 8]><div class="ltie8"><![endif]--> <div class="box photoL"> <div class="photo"><img src="images/tips/table_like_box_120.jpg" alt="任意の画像を挿入" /><p>画像の幅を自動取得しています。</p></div> <div class="comment">テーブルの様に、画像の大きさによってコメントボックスの幅が伸縮します。widthとheightを指定しなくても画像の大きさを自動で取得しボックスの横幅を計算します。<br />確認ブラウザ:IE6、IE7、firefox、opera、safari、Mac IE5</div> </div> <div class="box photoR"> <div class="photo"><img src="images/tips/table_like_box_120.jpg" alt="任意の画像を挿入" /><p>画像の幅を自動取得しています。</p></div> <div class="comment">テーブルの様に、画像の大きさによってコメントボックスの幅が伸縮します。<br />確認ブラウザ:IE6、IE7、firefox、opera、safari、Mac IE5</div> </div> <!--[if lt IE 8]></div><![endif]-->
CSSコード
.box { display: table; margin: 0 0 15px 0; width: 550px; background-color: #EEEEEE; } .photoR { direction: rtl; /*右から並べる*/ } .photoR * { direction: ltr; /*内容物は左から並べる*/ } .box .photo, .box .comment { display: table-cell; padding: 10px 0; vertical-align:top; color: #666666; font-size: 0.8em; line-height: 1.2em; } .box .comment { width: 100%; } .box .photo { padding-left: 10px; padding-right: 10px; } .photoR .comment { padding-left: 10px; } .photoL .comment { padding-right: 10px; } /* IE7以下に適用 */ .ltie8 .box .photo { width:expression(this.getElementsByTagName("img")[0].clientWidth);} .ltie8 .photoL .photo { float: left;} .ltie8 .photoR .photo { float: right;} .ltie8 .box .comment { width: auto;}
詳しい説明は長くなるのでしません。要はFirefox,Opera,Safariなどにはdisplay:tableを適用させ、IEにはexpressionを使って画像のサイズを取得し横幅を計算させているってことです。


















