Difference between DIV as-is and a SPAN with display:block

前端 未结 4 1330
夕颜
夕颜 2020-12-09 08:06

Is

different from in any way?

They render just fine the same. Any semantic difference b

相关标签:
4条回答
  • 2020-12-09 08:15

    Here's an example where it makes a real difference (for valid code, at least):

    <a href='example.com'>
        <span class='title' style='display:block;'>The title of the image is also a link</span>
        <img src="example.com/someimage.jpg"/>
    </a>
    

    That allows you to make your span a block level element and allows the image and span to highlight together when moused over.

    A div would not be valid nested inside an a tag.

    0 讨论(0)
  • 2020-12-09 08:21

    Yes. They can contain different things and are allowed in different places.

    They will also be rendered differently in environments where CSS is not available (e.g. in some email systems)

    0 讨论(0)
  • 2020-12-09 08:29

    Yes they are different.

    Even though you style a span with display: block you still can't put block-level elements inside it:

    <div><p>correct</p></div>
    <span style="display: block;"><p>wrong</p></span>
    

    The (X)HTML still has to obey the (X)HTML DTD (whichever one you use), no matter how the CSS alters things.

    0 讨论(0)
  • 2020-12-09 08:38

    A <div> is a block level element that has no specific semantics of its own, beyond defining a discrete block of content. A <span> is an inline element that has no specific semantics of its own, beyond defining a discrete segment of inline content.

    You can use CSS to make a span display as a block, but there is absolutely no reason to do so EDIT: other than for purely visual effects, as Gabriel demonstrates; what I mean is that you shouldn't use CSS to try to coerce a span into having block-level significance in terms of document structure. Furthermore, if you do, your content will probably appear meaningless to a user without CSS, such as a blind user, or a search engine.

    If it's a block, use a div. If it's part of inline content, use a span. Remember, CSS is about presentation alone; your markup still needs to be structured in a logical manner if your content is to be usable.

    See http://www.w3.org/TR/html401/struct/global.html#edef-DIV for the details.

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