December 17, 2004

Matrjoška Hack

For the few people who can not read Czech, I thought I would explain what is the Matrjoška hack. For the rest of you, you may divert your attention over to Pixy’s site.

What It Means To Me

I just can’t stand the Box Model. Many projects I do rely on a pixel-perfect design and I don’t have the energy to think about how much padding I need or how wide are my borders, just so the blocks will come out to being the correct widths. I like to set my blocks’ widths according to the design. Then if I want some padding inside a block, I will just give it some padding and be done with it. Nothing to worry about, except when you design for browsers other than Internet Explorer 5.x for PC.

According to the W3C, IE5.x renders the Box Model incorrectly. Gee, and I thought Microsoft was doing something right for once. If you need a remedial class on the problems with the Box Model, check out Tantek’s example page that includes his famous workaround (Tantek’s Box Model Hack).

Give Me The Goods

It’s simple really. Normally, we create one div for our block. But for this hack, we create two div blocks per “block.” In the stylesheet, we apply the exact width of our “block” to the outer block, which we have named myblock. Padding and borders are then applied to the inner block which, in the following example, is called myblockpad.

<div id="myblock">
<div id="myblockpad">

    Content goes in here.

</div>
</div>
#myblock {
    width: 250px;
}

#myblockpad {
    border: 5px solid #b00;
    padding: 10px;
}

Take a look at this example.

If you only wanted to use one div, you could apply the Box Model Hack. Of course, you would have to figure out both widths. To make the above example work correctly, you would take the width of the outer block and subtract the padding from both sides (that is 20px) and subtract the border from both sides (10px). Then you could include width, padding, and border in one div. Don’t forget the hack.

#myblock {
    border: 5px solid #b00;
    padding: 10px;
    width: 250px;
    voice-family: "\"}\""; /* box model hack */
    voice-family: inherit; /* box model hack */
    width: 220px;
}

html>#myblock {
    width: 220px; /* be nice to Opera */
} 

What a pain! Be nice to Opera? What did it ever do for me? I prefer the Matrjoška Hack.

Comments

And what about?:

#myblock { width:280px; }

#myblock * {padding:0 20px;}

Someone mentioned this trick somewere, and I found it very usefull.

This could work in some cases, but you would have to be careful as to what you put inside #myblock, because every element inside #myblock would get the padding treatment. Very interesting thought. I will keep this in mind. Thanks!

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

Posted in: