The CSS Box Model

Posted By: Ian on Mar 04, 2014 in CSS, Snippets
Last modified on January 29th, 2015 at 9:31 pm,

The Box Model

Margin Box
Border Box
Padding Box
Element Box

All elements are essentially boxes and these boxes enable us to be precise when placing our elements relative to others on our page.

REMEMBER!
When setting height and width in CSS you MUST take into account the padding, border and margin to get the TOTAL dimensions for the element. This is especially important when you want exact placement of your elements.

See it in action using this little snippet which will get the height, width, padding, border and margin of any element you click on.
<script>
$(document).ready(function () {
$("*", document.body).click(function (event) {
event.stopPropagation();
var domElement = $(this).get(0);
var t = $(this).width();
var y = $(this).innerWidth();
var p = $(this).outerWidth();
var e = $(this).outerWidth(true);
var g = $(this).height();
var o = $(this).innerHeight();
var l = $(this).outerHeight();
var d = $(this).outerHeight(true);
var dimensions = "";
dimensions += "Total width: " + t + " + " + (y - t) + " + " + (p - y) + " + " + (e - p) + " = " + e + "<br />";
dimensions += "Total height: " + g + " + " + (o - g) + " + " + (l - o) + " + " + (d - l) + " = " + d;
$("#box").html(dimensions);
}
);
}
);
</script>

Try Me

Too see all elements on a page in there boxes place a container div between the body tags with an id called container otherwise your see more elements counted than you can see as the head, body, script etc will be counted too.
<script>
var elementCount = $( "#container" ).find( "*" ).css( "border", "3px solid red" ).length;
alert(elementCount + " elements found");
</script>

Try Me

AnonymousIan.J.Gough

Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

leave a comment

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,
Ian.J.Gough

protected by copyscape duplicate content check

Categories


Powered by Banner Bar 125