0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【HTML・W3C Web standards】imgタグのwidth, heightには「負でない整数をピクセル単位で」指定しよう!

Last updated at Posted at 2023-10-14

🌻imgタグのwidth, heightには「負でない整数をピクセル単位で」指定しよう!

ネットでimgタグのwidth, heightについて検索すると
以下のように % で指定する例がヒットします。

<img width="100%" height="100%" />

ですが...

⏩W3Cが定めるWeb starndard的には「負でない整数をピクセル単位で」指定するのが正解です!

W3C Web standards の公式ページには、以下のように記載されています。
※W3C Web standards:Webのルールブックのようなもの。

・width = non-negative integer
 Give the width of the visual content of the element, in CSS pixels.

・height = non-negative integer
 Give the height of the visual content of the element, in CSS pixels.

要約すると
「負でない整数をピクセル単位で指定してね!」
と書いてあります。


⏩W3C Markup Validation Serviceでチェックするとエラーが出ます。

以下のように、width に % を含めたimgタグをコードに仕込んで、

<img src="./assets/images/img-concept01.png" alt="concept" width="100%" height="700" />

W3C Markup Validation Serviceでチェックしてみます。
※このツールで、HTMLが正しく記載されているかチェックできます。
※使い方は文末で紹介しています。

すると、以下のようなエラーメッセージが出力されます。
image.png

要約すると
「不正な値です。width に % は入れないで、数字だけ入力してね!」
と書いてあります。

heightも同じ挙動になります。


実際は、imgタグのwidthやheightに
・% を指定しても
・600.66 のように小数点を指定しても
Webページとして表示はできます。

が、標準化されたルール的にはNGのようです。


どうせならルールに則って正しいHTMLを書きたいですね!
いつどこでエラーが出るようになるか分からないですし…


ということで、これからは
imgタグのwidth, heightには
「負でない整数をピクセル単位で」指定しましょう!
※単位は不要です。


💡補足
・本件はあくまで「HTMLのimgタグ」に関するものです。
・CSSには % も vm もどんどん使ってください!

⏩おまけ①:iframeタグのwidthも同じ!「負でない整数をピクセル単位で」指定しよう!

iframeのwidthに関しても同様の記載があります。
こちらもやはり「負でない整数をピクセル単位で」指定しましょう。

・width
 The width of the frame in CSS pixels. Default is 300.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe

⏩おまけ②:HTMLが正しく記載されているか、W3C Markup Validation Serviceでチェックする方法

W3C Markup Validation Service
W3C.png

⏩おまけ③:CSSもチェックできます!

CSS Validation ServiceでCSSもチェックできます。
20231015-1.png


⏩おまけ④:関連ポスト

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?