Skip to main content

CSS box model margin and padding

Short answer

Use margin-right:10px on the left box to separate the boxes by 10px. Use padding-left:10px on each box to move the text right. Adding box-sizing:border-box keeps the widths fixed.

Given is the HTML code:

<html>
<head>
</head>
<body>
  <div style="padding:10px;float:left;">
    <div id="leftbox" style="width:100px;height:100px;float:left;border: solid 1px;">
      ON LEFT
    </div>
    <div id="rightbox" style="width:100px;height:100px;float:left;border: solid 1px;">
      ON RIGHT
    </div>
  </div>
</body>
</html>

The output of the above code is: [Figure: two boxes side by side, one containing "ON LEFT" and the other "ON RIGHT", each with a 1px solid border]

Use CSS Box model (margin/padding) to do the following: a. Separate left and right box by a total of 10 px b. Move text "ON LEFT" by 10 px towards right c. Move text "ON RIGHT" by 10 px towards right

The CSS box model has content, padding, border and margin. Margin creates space outside the border (between boxes); padding creates space inside the border (between border and content).

+-------------- margin --------------+
|  +---------- border ----------+    |
|  |  +------ padding ------+   |    |
|  |  |       content       |   |    |
|  |  +---------------------+   |    |
|  +----------------------------+    |
+------------------------------------+

a. Separate the boxes by 10 px

Put a right margin on the left box (or a left margin on the right box). Only one of them should get it, because two margins would give 20 px in total.

#leftbox { margin-right: 10px; }

b. Move "ON LEFT" 10 px to the right

Use left padding on the left box so the text is pushed inside it.

#leftbox { padding-left: 10px; }

c. Move "ON RIGHT" 10 px to the right

#rightbox { padding-left: 10px; }

Complete code

<html>
<head>
<style>
  #leftbox, #rightbox { box-sizing: border-box; }  /* keeps width 100px */
  #leftbox  { margin-right: 10px; padding-left: 10px; }
  #rightbox { padding-left: 10px; }
</style>
</head>
<body>
  <div style="padding:10px;float:left;">
    <div id="leftbox" style="width:100px;height:100px;float:left;border:solid 1px;">
      ON LEFT
    </div>
    <div id="rightbox" style="width:100px;height:100px;float:left;border:solid 1px;">
      ON RIGHT
    </div>
  </div>
</body>
</html>

The same rules can be written inline: style="...;margin-right:10px;padding-left:10px". Note: without box-sizing: border-box, padding is added to the 100 px width (the box becomes 110 px wide plus border), which is also acceptable if the box size need not stay fixed.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Web Technology chapter 2 questions →