Every element in HTML has a ‘box’ surrounding it. From text to images, the box model can be applied, and assists in the design and structure of your web page. The image below illustrates the 4 different properties of the box model.
There are 4 properties within the box model.
In your CSS code, you can define the size of each of these properties (apart from the content). Each property within the box model can be defined, to create spacing between elements.
There are 2 ways you can define the size you want the margin, border or padding to be.
- Length – you can define the sizes you want with pixels (px). You can set the size with pixels, this size therefore never changes once set, and will stay the same no matter what size window you have open. Example: padding: 20px;
Percentage – you can define the size with a percentage (%). This means the property will change size depending on the size of the window. Example: padding: 20%;
Individually vs Short-Hand
To set the distances you want for padding and margins, there are 2 ways you can do it, Individually or Short-Hand.
You can individually set each of the 4 sides of paddings/margins. The syntax to do so are:
For example if you wanted wide margins on the sides of your element but short margins vertically you could do:
However you can also write the same piece of code on just one line! This is shorthand. The example above in shorthand would look like this:
margin: 20px 100px 20px 100px;
The first value in shorthand is top. The second is right. The third is bottom. And the last value is left.
|padding: 10px 20px 30px 40px;|
You can also use shorthand to define one size for each of the 4 sides. For example, if you wanted all of the sides of padding to be 10px, then your code would look like this!