Differences between assigning attribute, style, and class in div

前端 未结 3 563
孤独总比滥情好
孤独总比滥情好 2021-01-26 16:38

I am wondering what is the difference between two following:

<
相关标签:
3条回答
  • 2021-01-26 16:55

    There are lot of pros and cons in both these approaches depending on the element and condition it should load/render. I don't think all of them can be explained in a single answer without giving various references in it.

    You can find such answers in the following questions:

    What's the difference between HTML's and CSS's width attribute?

    What's the difference between the HTML width / height attribute and the CSS width / height property on the img element?

    0 讨论(0)
  • 2021-01-26 17:02

    Having the style in an external CSS file allows it to be cached, reducing network traffic. Otherwise, it's the same as inline styling. The recommended form for inline styling is your latter proposal - style="width:100px;align:left" More here.

    0 讨论(0)
  • No, it's not equal, not even for only those two elements. The attribute width doesn't exist for the div element (and if it did, you wouldn't specify the unit, but only the numeric value in pixels). Yes, in HTML5 you can use pretty much anything as an attribute and get away with it, but HTML5 also suggests the use of CSS and only CSS for styling.

    Here's an example:

    div {height: 50px; background: #ccc; margin-bottom: 5px; display: inline-block; min-width: 100px;}
    div.css {width: 250px}
    <div width=250>Numeric</div>
    <div width="250px">Numeric w/unit</div>
    <div class="css">Regular CSS</div>

    As you can see, only the last example, Regular CSS, reads the actual width value. In case of align, that's a coincidental match, because there is an attribute align that was used heavily in HTML4 days (width and height were used a lot with images) and yes, it matches the CSS text-align rule. But that's not the case for all elements and attributes! Canvas, for example, uses the width attribute in a different manner than the width style (the attribute denotes the actual number of available pixels, while the style is just the size of the box element and can cause stretching, for example).


    The bottom line:

    Use CSS for styling/layout, use attributes for the rest.

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