Tell block elements apart from inline elements and learn the classic techniques for centering an element.
Open this lesson in KodokonHow do boxes arrange themselves on the page? It all depends on their display mode, controlled by the display property. A block element behaves like a brick: it takes up the full available width and pushes the next element onto a new line. Headings <h1>, paragraphs <p> and <div> tags (generic boxes with no particular meaning) are block by default. An inline element behaves like a word in a sentence: it only takes up the space of its content and sits next to its neighbors. Links <a> and <span> tags (the inline counterpart of <div>) are inline by default.
<p>A paragraph: I take up the full width.</p>
<p>Me too, so I start on a new line.</p>
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<span>A span, also on the same line.</span>The display property lets you change this behavior: display: block; on a link makes it take up the full width, display: inline; on a <div> makes it flow within the text. Watch out for an important limitation of inline elements: the width and height properties are ignored on them. To size an element, it must be block.
a {
display: block;
width: 200px;
background-color: lightblue;
}On to centering, the question every beginner asks. First case: centering text inside a box. The text-align: center; property is applied to the container and centers its inline content (text, links, images). Second case: centering an entire block box, such as a card in the middle of the page. The classic technique: give the box a width, then write margin: 0 auto;. The auto value asks the browser to work out the left and right margins itself: it makes them equal, which centers the box.
.card {
width: 300px;
margin: 0 auto;
text-align: center;
border: 1px solid gray;
padding: 16px;
}Let's recap what you have learned in this module: you know how to link a CSS file, write rules with selectors, properties and values, target elements by tag, class or id, balance padding, border and margin, style text and, now, arrange and center boxes. With these foundations, you can already build a simple, polished web page. The next module will introduce you to more powerful layout tools.
width: 200px; have no effect on a <span> by default?