In HTML5, a <div> is technically a block-level element, but behaves as an in-line element. Is this a special 'hybrid' element?

不打扰是莪最后的温柔 提交于 2019-12-06 12:51:02

问题


A block level element as defined by the W3Schools has having a line break before and after the element, such as p, h1, etc. Non nested inline elements either start on their own line (no line break) or remain on the same line if nested.

While span behaves normally (as well as all other inline elements). Div never creates line breaks like block elements all do, but only starts on a new line at the opening of the div element.

Perhaps I'm missing something since everyone talks about DIV being block level, but it behaves like an inline element in that it starts a new line if not nested, doesn't create line breaks, but acts like something else entirely that when a div is nested with another div it just creates a new line.

Is DIV the only "hybrid" element like this? Am I missing something more fundamental?


回答1:


No elements create line breaks. You're merely seeing the effects of different default styles, which have different margin and padding values. The default styles vary per browser, but often look something like the [very dated] reference stylesheet included with the HTML 4 spec: http://www.w3.org/TR/CSS2/sample.html




回答2:


The Mozilla Developer Network, or MDN, is the best place to learn about HTML.

There is an explanation of <div> here: div | Mozilla Developer Network:

The Document Division (<div>) HTML element is generic container for flow content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element (such as <article> or <nav>) is appropriate.

Here is the comparison between block-level and inline elements:


Block-level elements:


The differences between inline and block-level elements are:

Formatting

By default, block-level elements begin on new lines.

Content model

Generally, block-level elements may contain inline elements and other block-level elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.


Inline elements:


Differences between inline and block-level elements:

Content model

Generally, inline elements may contain only data and other inline elements.

Formatting

By default, inline elements do not begin with new line.



来源:https://stackoverflow.com/questions/12289288/in-html5-a-div-is-technically-a-block-level-element-but-behaves-as-an-in-lin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!