DrillLab
第 1 / 105 道1 / 105 · #269

块级元素 vs 行内元素

Block element vs Inline element

先自己答,再往下看Answer it yourself first

一句话:块级元素独占一行、宽高可控; 行内元素跟着文字流走、宽高由内容决定。

具体差别就三处,记住这三条就够答:

  • 换行—— 块级前后自动断行(divph1ul); 行内不断行(spanastrongimg)。
  • 宽高—— 块级可以设 width /height;行内设了不生效
  • 内外边距—— 块级四个方向都生效; 行内的上下 margin 不生效, 上下 padding 视觉上会溢出但不撑开行高。

会追问:「那 inline-block 呢?」 —— 它是折中:不换行(像行内),但宽高和上下 margin 都生效(像块级)。 导航按钮常用它。

还会追问:img 是行内元素, 为什么能设宽高?」—— 因为它是替换元素(replaced element), 内容由外部资源决定,浏览器对它网开一面。inputvideo 同理。 这个点答出来会加分。

In one line: a block element takes the whole line and you can set its width and height; an inline element flows with the text and is sized by its content.

There are exactly three differences worth remembering:

  • Line breaks — block elements break before and after (div, p, h1, ul); inline ones do not (span, a, strong, img).
  • Width and height — settable on block elements, ignored on inline ones.
  • Margin and padding — all four sides work on block elements; on inline elements vertical margin does nothing, and vertical padding overflows visually without pushing the line apart.

Follow-up: “What about inline-block?” — it is the compromise: no line break (like inline) but width, height and vertical margin all work (like block). Nav buttons use it constantly.

Also asked:img is inline, so why can you set its size?” — because it is a replaced element: its content comes from an external resource, so the browser makes an exception. Same for input and video. Getting this one right scores points.