How do block elements differ from inline elements?
The main difference:
Block elements form a new block, take up the full available width, and start on a new line. Inline elements do not start a new line and take up only the space their content needs.
Detailed explanation (great for an interview)
Block elements (block)
-
Always start on a new line
-
Take up the full width of the parent by default
-
Can be given:
-
a width (
width) -
a height (
height) -
outer margins (
margin) -
inner spacing (
padding) -
borders (
border) -
Behave like rectangular blocks in the document flow
-
Are often structural elements
Examples of block elements:
<div>, <p>, <section>, <article>, <header>, <footer>, <h1>-<h6>.
Inline elements
-
Do not start a new line: they sit "within the line"
-
Width depends only on the content
-
Cannot be given:
-
a width
-
a height
-
Spacing works in a limited way:
-
vertical
margindoes not affect the flow -
vertical
paddingandborderdo not push neighboring elements, they just "stick out" within the line -
Used to emphasize text or small elements
Examples of inline elements:
<span>, <a>, <strong>, <em>, <label>, <img> (partly inline-block).
Table comparison (very handy for an answer)
| Property | Block | Inline |
|---|---|---|
| Starts a new line | Yes | No |
| Takes up the full width | Yes | No |
| Width/height work | Yes | No |
| Margin/padding on all sides | Yes | Partly |
| Used for structure | Yes | No |
| Used within text | No | Yes |
There is an intermediate type: inline-block
Interviewers often ask about it.
- Does not wrap to a new line
- But width/height can be set
- Behaves like a hybrid of block and inline
Example: <img>, <button>, <input>.
Short definition (if asked briefly)
Block elements form a new block and take up the full available width. Inline elements sit within the line, take up only the size of the content, and cannot have width/height applied to them.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.