Crus4

logo

CSS Padding


The CSS padding property is used to create space around an element’s content, inside the specified borders.

So, CSS margin property is used to create space around element’s, outside the specified borders and the CSS padding property is used to create space around element’s, inside the specified borders.

With CSS, we have full control over the padding. We can setup the padding for each side of an element (top, right, bottom & left) by using the following properties:

These padding properties can have the following values:

NOTE:- Unlike margins negative values are not allowed here.

In an example below let’s write a code where we set different padding for all four sides of an p element.

<!DOCTYPE html>
<html>
<head>
<style>
p {
  border: 1px solid black;
  background-color: lightblue;
  padding-top: 50px;
  padding-right: 30px;
  padding-bottom: 50px;
  padding-left: 80px;
}
</style>
</head>
<body>
<h1>Using individual padding properties</h1>
<p>This element has a top padding of 60px, a right padding of 30px, a bottom padding of 50px, and a left padding of 60px.</p>
</body>
</html>

padding-shorthand

By writing the code like we write in an above example, can makes a code lengthy and difficult to read. Because we have write all four padding properties (top, right, bottom, left) in a separate lines.

So, to shorten the code and make it easy to read, we can define all the padding properties in a single line. Like this:

p {
  padding: 50px 30px 50px 80px;
}

Now to test it whether it works or not let’s put the same code in a below example.

Example

<!DOCTYPE html>
<html>
<head>
<style>
p {
  border: 1px solid green;
  padding: 60px 30px 50px 60px;
  background-color: lightblue;
}
</style>
</head>
<body>
<h1>Using individual padding properties</h1>
<p>This element has a top padding of 60px, a right padding of 30px, a bottom padding of 50px, and a left padding of 60px.</p>
</body>
</html>

If the padding property has 3 values, like this:

p {
  padding: 40px 60px 75px;
}

In that case, top padding is 40px, right and left paddings are 60px and bottom padding is 75px.

If the padding property has 2 values, like this:

p {
  padding: 40px 75px;
}

In that case, top and bottom paddings are 40px and right and left paddings are 60px.

If the padding property has only 1 value, like this:

p {
  padding: 40px;
}

In that case, all four padding properties are 40px.


CSS Padding