November 2, 2012

Containing the box size


Containing the width of a box to a fixed size is really important while making a webpage. But setting the width and adding padding, borders and margins makes the box larger than the actual size. This tutorial will give a technique that makes the box to contain within a fixed size.

Situation and problem

To understand the situation, let us make a box element and set a width of 180 pixels. Now add padding of 10 pixels and border of 5 pixels. Now the box becomes 210 pixels.


p {
  width: 180px;
  padding: 10px;
  border: 5px solid #069;
}



As you see above the width do not contain but expand, but this now will become a problem when you need to contain the box to give some space to the other boxes in a webpage.

Consider two contents of 180 pixels wide which needs to fit into a 380 pixels wide container which is easily possible and that also leaves another 20 pixels of space. But after applying padding and borders, it seems that it is impossible now to fit into the container.

Solution to this problem

The solution to this can be solved by placing the element inside a div tag and setting a width to it. Now, even if the element inside this div tag add padding, borders or even margins it will be contained within the outer div tag's width.


div.container {
    width: 180px;
}

p {
    margin: 10px;
    border: 5px dashed #069;
    padding: 10px;
}

Now by using this outer div containers, you can set a fixed size to any element and the box do not change size.

No comments:

Post a Comment