Connect with:
About Me
Alessandro Annini
I'm a freelance developer currently working at I really love framework and its amazing potential and if you're like me, and you want the web to win, please share some snippet of code for the community and grow faster with us
Meta Code | Quickly setting margins using BoxLayout

Quickly setting margins using BoxLayout

14 Jul Quickly setting margins using BoxLayout

Sometimes you need to specify margins for a renderable relative to it’s parent. You can use modifiers to change the size and the offset. This is pretty straightforward, but can only be done when you know the size of the parent:

// parent with fixed size
var parent = new Modifier({
    size: [200, 200]
// create 20px margin all around
var modifier = new Modifier({
    size: [160, 160],
    transform: Transform.translate(20, 20, 0)
var front = new Surface({ properties: { backgroundColor: 'blue' }});

Alternatively, you can use layout-views such as FlexibleLayout or GridLayout to create a margin for this. The example below shows the use of a FlexibleLayout to create a 20px margin to the left and right.

// create layout with 20px margins left and right
var flexibleLayout = new FlexibleLayout({
    ratios: [true, 1, true],
    direction: 0
    new RenderNode(new Modifier({size: [20, undefined]})),
    new RenderNode(new Modifier({size: [20, undefined]}))

Note that it takes a quite a bit of (too) complicated code to get the left and right margins working. It gets ever more complicated when you need to nest LayoutView to achieve top and bottom margins as well.

To make settings margins easier, I decided to write a solution for it. The result is a lightweight class called BoxLayout. BoxLayout internally uses FlexibleLayout to achieve its layout. It hides the technicalities of setting margins using FlexibleLayout and offers a more convenient interface:

// create layout with 20px margins all around
var boxLayout = new BoxLayout({
    margins: [20]

The margins option works exactly the same as the CSS-style margins. It accepts the margins all around as a clockwise array. Short-hand notation is also supported. Additionally, renderables can be added not only to the middle of the box, but to any of the marginated areas (top, right, bottomLeft, etc…).

// create layout with 20px top margin, 30px right margin and 50px left margin
var boxLayout = new BoxLayout({
    margins: [20, 30, 0, 50]
// add red surface to right-area Surface({ properties: { backgroundColor: 'red' }});

The component is installable using bower and can be found here: