The margin property in CSS is used to create space around elements, outside of any defined borders. The margin property can be set individually for each side or as a shorthand for all sides.
Syntax:
Individual Properties:
- margin-top: value;
- margin-right: value;
- margin-bottom: value;
- margin-left: value;
Shorthand Property:
margin: [top] [right] [bottom] [left];
Shorthand Values:
1. One Value:
/* All sides will have 10px margin */
p {
margin: 10px;
}
container1
All sides will have 10px margin
2. Two Values:
/* Vertical (top and bottom) margins are 10px, horizontal (right and left) margins are 20px */
p {
margin: 10px 20px;
}
container1
Vertical (top and bottom) margins are 10px, horizontal (right and left) margins are 20px
3. Three Values:
/* Top margin is 10px, horizontal (right and left) margins are 20px, bottom margin is 30px */
p {
margin: 10px 20px 30px;
}
container1
Top margin is 10px, horizontal (right and left) margins are 20px, bottom margin is 30px
4. Four Values:
/* Top margin is 10px, right margin is 20px, bottom margin is 30px, left margin is 40px */
p {
margin: 10px 20px 30px 40px;
}
container1
Top margin is 10px, right margin is 20px, bottom margin is 30px, left margin is 40px
Auto Margin: You can use margin: auto; to center an element horizontally within its container. This works when the element has a defined width.
/* Horizontally centering a block element */
.centered {
width: 50%;
margin: 0 auto;
}
Negative Margins: Negative values are allowed for margins, which can pull elements closer together.
/* Negative margin example */
.negative-margin {
margin-top: -10px;
}
CSS Margins – Interview Questions
Q 1: What is margin in CSS?
Q 2: How many sides can margin be applied to?
Q 3: What is margin shorthand?
Q 4: Can margins have negative values?
Q 5: What is margin: auto used for?
CSS Margins – Objective Questions (MCQs)
Q1. Which property is used to create space outside the element?
Q2. Which margin value centers a block element horizontally?
Q3. Which property sets left margin?
Q4. Which syntax sets margin for all four sides?
Q5. Negative margin values are: