In this tutorial, we will learn about CSS Margins. CSS margin property is used to set space around the HTML elements. CSS margin property can be used to set margin separately for each side(top, right, bottom, and left) or together to all four sides.
Page Contents
Setting Margin Individual Sides:
There are four CSS properties to set the margin for each side. These are as follow:
- margin-top
- margin-bottom
- margin-right
- margin-bottom
p {
margin-top: 20px;
margin-bottom: 20px;
margin-right: 25px;
margin-left: 25px;
}
In margin properties we can use the following values:
- auto – the browser automatically calculates the margin for element
- length – use simple px, pt, cm, values to mention margin.
- % – specifies a margin in % of the element
- inherit – it means margin should be inherited from the parent element
p {
margin-top: 20px;
margin-bottom: 20px;
margin-right: auto;
margin-left: auto;
}
Shorthand Margin Property:
Shorthand margin property used to specify the margin for all four sides in a single line. Please check the following example:
p {
margin: 15px 20px 30px 25px;
/* top margin is 15px */
/* right margin is 20px */
/* bottom margin is 30px */
/* left margin is 25px */
}
CSS margin property with three values:
p {
margin: 15px 20px 25px;
/* top margin is 15px */
/* right and left margins are 20px */
/* bottom margin is 25px */
}
CSS margin property with two values:
p {
margin: 15px 20px;
/* top and bottom margins are 15px */
/* right and left margins are 20px */
}
CSS margin property with a single value:
p {
margin: 15px;
/* margin of all four sides is 15px */
}
Parvesh Sandila is a results-driven tech professional with 8+ years of experience in web and mobile development, leadership, and emerging technologies.
After completing his Master’s in Computer Applications (MCA), he began his journey as a programming mentor, guiding 100+ students and helping them build strong foundations in coding. In 2019, he founded Owlbuddy.com, a platform dedicated to providing free, high-quality programming tutorials for aspiring developers.
He then transitioned into a full-time programmer, where his hands-on expertise and problem-solving skills led him to grow into a Team Lead and Technical Project Manager, successfully delivering scalable web and mobile solutions. Today, he works with advanced technologies such as AI systems, RAG architectures, and modern digital solutions, while also collaborating through a strategic partnership with Technobae (UK) to build next-generation products.
