Search code examples
htmlcsswidthinlinepixel

Omitting pixel when using inline "width"


A bit of a silly question but important for me to understand. As far as I know when using the inline "width" attribute in HTML, it is permitted to omit "px" - - will automatically be understood as "20px" unless percentage("20%") is used. My question is: Is it wrong to use the "..px" even though it's not needed? The code seem so much cleaner to me, it follows the same rule as CSS and least but not last - it doesn't bug me anytime I look at it. Thanks in advance.


Solution

  • This is never stated outright in the HTML 4 or older specs, but all HTML DTDs that support width and related presentational attributes don't impose any restrictions on %Pixels values — they simply state in prose that they should be integers, but are defined in the DTD as CDATA:

    <!ENTITY % Length "CDATA" -- nn for pixels or nn% for percentage length -->
    <!ENTITY % Pixels "CDATA" -- integer representing length in pixels -->
    

    So, technically, it's not wrong, in fact you could put anything you want and

    1. it'd still validate against the HTML 4 DOCTYPE; and
    2. browsers would simply parse the attribute value as either an integer or a percentage.

    All of the following are functionally equivalent, producing tables that are 200 CSS pixels wide (because none of the values can be parsed as a percentage):

    <table border="1" width="200"><tr><td><code>width="200"</code></table>
    <table border="1" width="200px"><tr><td><code>width="200px"</code></table>
    <table border="1" width="200abcd"><tr><td><code>width="200abcd"</code></table>
    <table border="1" width="200x10px"><tr><td><code>width="200x10px"</code></table>