CSS box model once and for all

From time to time, I forget the workings and attributes of the CSS box model. So, this time, I decided to write a blog post summarizing it and highlighting its logic. I hope this will make it easier to retain it.

In order to understand the box model, this post will be broken down in several sections relating to the model attributes. First, we’ll go over the existing types of boxes; then, how they are sized, positioned and floated; finally, how to make them responsive to the screen size.

Types of boxes

With the display attribute we can set the type of box we are using, for example

This div has attribute display: block. The borders are in black, so you can see that it stretches as far as it can to the left and to the right.

This one is a display: inline element. Its contents are wrapped inside a box that can be inlined with other inline elements.

With a display: none style, the element will not be rendered at all. This is different from the visibility: hidden style, in which the elements exist, take space, but are not shown.

Box sizing

The sizing of the box is defined with the width and height attributes. By default, this measure is of the content part only, so additional padding, border or margin add up to the total size of the box. This means that if you want the whole box (content + padding + border + margin) to fit a precise space, you need to do some math.

An alternative to this is to set the sizing measure to box-sizing: border-box. In this mode, the width and height defined will be the sum of the content, padding, border and margin. For example:

This box has width: 300px and
box-sizing: content-box (the default)
As you can see, the content measures 300px, but the border occupies an additional 10px
This other div has width: 300,
but box-sizing: border-box
So 300px is the measure of the entire box!

Since this is a recent addition to the CSS standard, some browser may require specific css tags to switch to box-sizing:

-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;

To apply this to all elements, just set the CSS style for all elements:

* {
-webkit-box-sizing: border-box;
   -moz-box-sizing: border-box;
        box-sizing: border-box;
}

Box Positioning

There are 4 attributes for positioning:

  • position: static the element follow the flow of the page and is considered to be not positioned – as a visual reminder, it’s flagged in red. The other attributes, in green, are considered positioned.
  • position: relative the element is translated, with the attributes left, right, top and bottom, relative to where it would be positioned. The element is translated, but it still occupies the original space in the document. In this sense it can overlap other elements and leave blank gaps in the document, as we will see in an example below.
  • position: absolute positions absolutely in relation to the parent box, which must have a positioned attribute (the green ones). It can be positioned using the left, right, top, bottom attributes.
  • position: fixed the element is fixed to the viewport. The box can be positioned using the left, right, top, bottom attributes.

In order to illustrate the types of positioning, some examples:

  • A relatively positioned div
a positioned div (position: relative)
a translated position: relative div overlapping the one above and leaving a blank space where it was located
another positioned div (position: relative)

  • A absolutely positioned div
a positioned div (position: relative)

a div absolutely positioned (position: absolute)

A fixed div… check the bottom right of your screen 😉

I’m a position: fixed div

Floating boxes

An element can be “floated” in order to wrap text around it:

I’m float: left !

In order to demonstrate the text wrapping, I’ll write a text that is long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long.
As you can see, it wraps around the float!

The problem with the floats is that the following div is still locked on the float:

I’m floated!

This div respect the float and wraps nicely around it.

This next div is locked on the float…

If the next div must break free from the float and appear after the floated element, it suffices to clear: left | right | both the float:

I’m floated!

This div respect the float, but the next one will break free from the float and appear below.

I’m a clear: left div, free from the float!

This float thing can be used to build a responsive web site. Try to resize the screen to see what happen to these divs:

float: left – A
float: left – B
float: left – C

Since they are floated, when there’s no more horizontal space, they are stacked on top of each other. Pretty nice, hum? But there’s more to responsiveness…

Responsive layout

The layout of the page can be changed depending on the size of the viewport using @media queries. When the query is valid, it is triggered, applying the designated styles. For example a menu on the left

Could be stacked on the top of the section when the screen becomes too small:

This is achieved with the following CSS

@media screen and (min-width: 600px) {
   nav     { float: left;
             width: 25%;}
   section { margin-left 25%}
}

@media screen and (max-width: 600px) {
   nav li  {display: inline }
}

The first block is applied when the viewport width is at least 600px. It aligns the nav to the left and the section to the top. If the screen size is under 600px, the first block of styling is not applied and the second one is. In this case, the divs will follow the usual behavior of occupying all the horizontal space and being one after the other.

Final Words

I believe this short summary could be used as cheatsheet when in doubt about the box model. I hope you enjoyed it.

A final remark, there’s an upgrade to the box model that is under development: the flexbox. This will be the subject of another post.

Advertisements

Dynamic vs. Static Typing

TL;DR: I’m sharing my view on Static vs. Dynamic typing after watching the Programming Languages Course @ Coursera. In the table below the key highlights:

Static typing Dynamic Typing
The object’s types are checked by the type checking system before the program is run The program is run without any type validation, it’s the developer’s burden to code the checking for when the program is executing (runtime)
At every part of the program the type of the objects used are known, so one’s assured that the right type of objects are being passed in the right places The type of the objects are known only at runtime. So if a wrong object type is being used, it will only show up during execution as a runtime exception.
The structure of the program is somewhat rigid, since a type must be defined for everything that is used Dynamic typing languages are more flexible, since you do not need to respect the type system
Changes in the program’s types structure are flagged by the type checking system and must all be corrected before running the program. Propagating changes in the type structure is responsibility of the developer, but subparts can be run before all the changes are implemented.

A few times I’ve tried understanding Dynamic vs. Static, but I never quite grasped it. I believe I didn’t get it because the mental model I was using wasn’t in line with what the writer had on it’s own, so we weren’t communicating on the same abstraction level.

It was during the Programming Language Course @ Coursera (a course that I strongly recommend if you don’t have a formal CS degree like me), that the professor, Dan, explained it in a way that finally made sense to me. In case there are other people wandering around, struggling to understand it, here’s my take on the subject:

  • Static Typing: it means that the types are/must be defined before the program executes (in a “static” environment). This done automatically by the type checking system, in which the object’s types are known at every line of the code. Therefore, before the program is even executed, there are no worries that there is a different than expected object being passed around. For example, if there is an object Foo being passed to a function, where an Array was expected, the type checking would fail before the program even start running. On the other hand in …

  • Dynamic Typing: there are no checks before the program is run. Any object type can be passed anywhere, provided that the syntax of the language is respected. For example, the if-then-elses parts must be in the correct order, but the language doesn’t care if there is a non-bool in the “if” part, or if the return types from the then/else branches are different. This means that in the code, objects of different types can be passed around without any restriction or error. The burden of type checking is passed to the developer.

    In case there are objects being passed with different types than expected, like in the previous example, it will be only at runtime that an exception will be thrown and the developer will be aware of the error. Since there’s no type checking system to watch over one’s shoulder, usually there are helper functions, like “is-of-type-X?” or similar, that will do the checking while the program is running (hence “dynamic” typing).

Spreadsheets and Excel – the “open source” modelling tool

In my life I had alternated periods of time in which I used Excel. I always wondered why such a simple tool has became so successful among people and companies. I was struck with the idea that a spreadsheet is an “open source” modelling tool.

The building block of the spreadsheets is very simple: just some cells in which you type formulas. The nice thing about this – macros apart – is that whatever is being calculated, you can take a peek inside it. In this way, you can walk your way through the document and understand every detail of what’s being modeled.

Other modelling softwares are usually more powerful, but they require the user to study and have deeper knowledge of the tool. The user is required to understand the inner workings of each functionality and each command. It’s not just “open document, start exploring”.

Moreover, the cells enforce the Functional paradigm, so that a formula contains reference to other cells only. There is no concept of state, no “for” loops, no local variables that you have to store in your brain to understand what’s happening.

Another point is that there is a limited set of functions and operations that one can use. This narrows the complexity the model can have. It either must comply with what’s available – and eventualy trade off a better quality model for simplicity – or be modeled elsewhere, in more powerful tools such as Matlab. In this sense, a spreadsheet is a threshold for model simplicity.

So let’s praise the spreadsheets for their simplicity and success!

Bitcoin market in Brazil – slowly spreading

Abstract: my experience trying to buy Bitcoins in Brazil and some references on where to buy’em without having to resort to expensive bank transfers — use them at your own risk.

About six months ago the Bitcoin slowly started entering mainstream journals headlines. It has been around for years, but the buzz on this technology started getting louder and it caught my attention. I decided to buy some Bitcoins, just in case it would get traction in the coming years, but I wanted cheap options that wouldn’t involve sending my money internationally through expensive banks mechanisms.

At the time, few options were available, one was Mercado Bitcoin, but I had the misfortune of finding it around March 2013,  just before it got hacked and all operations were suspended. Today this website is already back on, but I was disappointed a missed the big BTC rally.

As there were no easy alternatives, it meant that there are probably important things to happen in this market. Other options I found were

  • Bitcoin-OTC – over the counter trades in which users are free to negotiate how they want to proceed their exchanges. It’s well organized, has an order book and a web of trust in which users are rated. Negotiations takes place in a mIRC channel on FreeNode.
  • Local Bitcoins – provides a trading environment between users. It has a nice escrow system in which the website is the trusted third party that holds and releases the Bitcoins while the trade occurs. It is also the last instance judge in case of dispute between users.

Another alternative that worked for some time was BitInstant, in which you could transfer money to a brazilian bank and it would credit directly into a MtGox account. But since a few months ago, it stopped working in Brazil.

Just today I found two new websites that I haven’t yet tried out (use at your own risk), but it could be a sign the at last Bitcoin is entering brazilian territory:

Considering the trend that some places are considering it a legal tender, Brazil could follow suit (as usual) their peers. This would be great news for the currency in this part of the world.