In this tutorial, we'll focus on how to effectively set margins and padding for your HTML elements. These are key aspects of controlling the layout and alignment of your content on a webpage.
By the end of this tutorial, you will learn:
Margins and padding are key properties in CSS that control the space around elements.
Margin is the space outside the border of an element, while padding is the space inside the border of an element.
To set the margin of an element, use the margin
property. This can be set as a specific measurement (like 10px
) or as a percentage of the containing element.
div {
margin: 10px;
}
To set the padding of an element, use the padding
property. This is also set as a specific measurement or a percentage.
div {
padding: 20px;
}
margin: 10px 15px;
) to set multiple values at once. The first value is the top and bottom margin, and the second is the left and right margin.<div class="content">
Hello, World!
</div>
.content {
margin: 15px;
/* This sets a margin of 15px on all sides of the .content div */
}
<div class="content">
Hello, World!
</div>
.content {
padding: 15px;
/* This sets a padding of 15px on all sides of the .content div */
}
In this tutorial, we covered setting margins and padding in CSS. We learned the difference between the two and how to set them using different units of measurement.
Next, you may want to learn about other CSS properties like border
, outline
, and box-sizing
.
For more in-depth information, refer to the MDN Web Docs.
Create a div
with a class of example
, and give it a padding of 20px
and a margin of 30px
.
Create a p
tag with a class of text
, and give it a padding of 10px
and a margin of 5px
.
<div class="example">This is an example div</div>
.example {
padding: 20px;
margin: 30px;
}
<p class="text">This is an example paragraph</p>
.text {
padding: 10px;
margin: 5px;
}
Keep practicing with different elements and values to get a better understanding of how margins and padding work in CSS.