CSS Margin Properties

CSSWeb DevelopmentFront End Technology

The CSS margin property is a shorthand for margin-top, margin-right, margin-bottom, and margin-left. It enables us to specify the space around elements. We can also set margins for individual sides.

Syntax

The syntax of CSS margin property is as follows −

Selector {
   margin: /*value*/
}

Example

The following examples illustrate CSS margin property −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
div {
   margin: 10px 50px 20px;
   padding: 1rem;
   border: dashed;
}
p {
   text-align: center;
}
#demo {
   margin-left: -80px;
   box-shadow: inset 0 0 10px brown;
}
</style>
</head>
<body>
<div></div>
<p>This is demo text.</p>
<p id="demo">Another demo text.</p>
<p>This is new demo text.</p>
</body>
</html>

Output

This gives the following output −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
ul {
   margin: auto;
   background-image: linear-gradient(to right, khaki, aliceblue, skyblue, rebeccapurple);
   width: 20em;
}
li {
   margin-top: 3px;
}
li + li {
   margin-left: -20px;
}
li:last-child {
   margin-left: 75px;
}
</style>
</head>
<body>
<h2>Demo Heading</h2>
<ul>
<li>This is demo list item.</li>
<li>This is another list item with different style.</li>
<li>This is our third demo text with another style.
</li>
</ul>
</body>
</html>

Outline

This gives the following output −

raja
Published on 08-Jan-2020 07:45:49
Advertisements