style width vs width attribute in HTML

前端 未结 3 797
渐次进展
渐次进展 2021-01-12 16:16

I saw last post similar to my question HTML5 canvas style height vs attribute height
But in that post, there was no clear information regarding which one will work and

相关标签:
3条回答
  • 2021-01-12 16:57

    For most html elements, width attribute has nothing to do with the element's width. What defines an element's style(certainly contain width) is the element's style attribute.

    In other words, the style.width(style="width: 200px;") attribute determines the element's width.

    But some elements like canvas, svg, the width attribute will determines the element's width, if you don't set style.width attribute. In this case, width="200px" is the same as width="200" because most browsers use the px as default unit.

    PS:

    • The width is invalid to set the select's width.
    • But the width attribute is valid. You can access it and change it with freedom. You can use it to do other things.
    0 讨论(0)
  • 2021-01-12 17:04

    The width attribute is invalid in a select element. What matters more, this restriction is imposed by browsers: they ignore the attribute. (Long time ago, Netscape 4 supported it, and it was described in the HTML 3.0 draft, which expired in 1995. Some legacy code, maybe even legacy coding practices, may still reflect such things!)

    So answer is simple: they differ so that the width attribute in HTML has no effect (so the element takes its default width), whereas the width property in CSS works in the normal CSS way.

    The width attribute is not a general attribute in HTML: it is allowed for a certain set of elements and defined individually for them.

    0 讨论(0)
  • 2021-01-12 17:08

    1) <select style="width: 200px"> style here is the attribute of <select> HTML element, what is written inside the quote is CSS code. Likewise, <select width="200px"> width here is the attribute of <select>. However,<select> tag doesn't have width attribute see here (under attributes) More information on HTML attributes: here

    see DEMO

    2) width="200" is equivalent to width="200px"

    0 讨论(0)
提交回复
热议问题