Computer >> Computer tutorials >  >> Programming >> CSS

Setting Margin Space around elements using CSS


The CSS margin property is used to set the margin area around the selected element around its borders. The margin property is a shorthand for margin-top, margin-right, margin-bottom, and margin-left.

Syntax

The syntax of CSS margin property is as follows −

Selector {
   margin: /*value*/
}

The following examples illustrate CSS margin property −

Example

<!DOCTYPE html>
<html>
<head>
<style>
body * {
   display: flex;
   float: left;
   margin: 10px 15px;
   border: thin solid;
   text-align: center;
   width: 40%;
   border-radius: 5%;
   box-shadow: 0 0 4px 1px grey;
}
p {
   font-family: "Sim Sun", monospace;
   background-color: lightcyan;
}
div {
   font-family: Impact, cursive;
   background-color: lightgreen;
}
</style>
</head>
<body>
<p>First demo text</p>
<div>A demo line goes like this..</div>
</body>
</html>

Output

This gives the following output −

Setting Margin Space around elements using CSS

Example

<!DOCTYPE html>
<html>
<head>
<style>
table, table * {
   margin: 5% 30%;
   border: 12px double red;
   padding: 0.5rem;
   border-radius: 30px;
}
td:nth-child(even) {
   background-color: lightblue;
}
td:nth-child(odd) {
   background-color: lightgreen;
}
</style>
</head>
<body>
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>

Output

This gives the following output −

Setting Margin Space around elements using CSS