How to make a distance between blocks in CSS
Learn how to create space between blocks in CSS with an example: margin & padding properties, box-model & flexbox.
Creating Distance Between CSS Blocks with Margin
Creating distance between blocks in a webpage is a common practice. To do so in CSS, you can use the margin
property. The margin
property allows you to create space around an element, outside of any defined borders. The margin
property can take up to four values, which can be specified in different ways.
/* All four values are the same: */
margin: 10px;
/* Top & Bottom are 10px, Right & Left are 5px: */
margin: 10px 5px;
/* Top is 10px, Right & Left are 5px, Bottom is 20px: */
margin: 10px 5px 20px;
/* Top is 10px, Right is 5px, Bottom is 20px, Left is 15px: */
margin: 10px 5px 20px 15px;
You can use the margin
property to create distance between blocks. If you want to create a space of 10px between two blocks, you can add the margin
property to the second block, like so:
<div class="block1">
This is block one!
</div>
<div class="block2" style="margin-top: 10px;">
This is block two!
</div>
In the example above, we have added a margin-top
of 10px to the second block. This will create a distance of 10px between the two blocks. You can also use the margin
property to create space around the entire block. For example:
<div class="block1" style="margin: 10px;">
This is block one!
</div>
<div class="block2">
This is block two!
</div>
In the example above, we have added a margin
of 10px to the first block. This will create a distance of 10px around the entire block. You can also use the margin
property to create space around the entire block. For example:
<div class="block1" style="margin: 10px 5px;">
This is block one!
</div>
<div class="block2">
This is block two!
</div>
In the example above, we have added a margin
of 10px to the top and 5px to the bottom of the first block. This will create a distance of 10px at the top and 5px at the bottom of the block.
The margin
property is a powerful tool for creating distance between blocks. You can use it to create space around individual elements, or around an entire block. By using the margin
property, you can easily create the distance between blocks that you need.