The Golden Ratio in Web Design

Math is beautiful. Does that sound a little strange? I sure thought so when I first started designing. Math is so rigid and often times boring, or so I thought. You would be surprised to find out that most aesthetically pleasing designs, works of art, objects and even people have math in common. Specifically the Golden Ratio, also known as the divine proportion, which is designated by the Greek letter Φ (phi). This tutorial will cover the anatomy and layout of a website and how the Golden Ratio relates.
The elements of a web page are like organs; they are vital to a properly functioning and aesthetically pleasing web page.

These are the main elements of a web page. There are many different ways to organize them but this is perhaps the most common basic layout used online.
All web pages use a container and for the same purpose; to contain page elements, however the way it is accomplished varies. For example, the body tag or a div is most commonly used. In the past, even a table has been used (do not use a table as your page container, it is a depreciated method). Think of the container as the external walls of your house in which your bedrooms, kitchen, living room, etc. are then placed.
Types of container:
  1. Liquid: Expands to fill the width of the browser window.
  2. Fixed: A specific width you choose which does not change regardless of browser window size.

The header isn't really a specific element although some may consider it to be. It is more generally used in referring to the top section of your web page where your logo, navigation, tagline, etc. are located. Many people prefer to keep these elements contained within a div for easier page styling, element separation and/or element containment. The header would be considered a container so it would have two types to choose from: liquid or fixed as mentioned above.

Your logo is your identity and branding. The most common placement for the logo is within the header, aligned left. We read from left to right, top to bottom, so your logo will most likely be the first element your visitors look at.
Page navigation is one of the most important elements; your visitors need it to use your website. It should be easy to find and use, which is why it is almost always located within the header or at least near the top of the page. Sometimes both types of navigation are used for high content websites.
Types of navigation:
  1. Horizontal: A series of links displayed inline, usually referred to as "navigation".
  2. Vertical: A series of links displayed as a vertical stack, usually referred to as "menu".

As everyone knows (or should), content is king! When people visit your site, this is the element they will be looking for primarily. It should be the main focal point of a web page so visitors find what they are looking for quickly.
The sidebar is the element with your secondary content such as advertising, site search, subscription links (RSS, Twitter, Email, etc), contact methods, etc. This element isn't necessary although many websites use it. It is most often right aligned but can be left aligned or both (two sidebars) so long as it doesn't disrupt main content viewing. For websites that use horizontal AND vertical navigation, the sidebar is often replaced with the vertical navigation element.

The end of a web page should always use a footer to let your visitors know they have reached the completion of your web page. Like the header, the footer isn't really a specific element but more of a containing section. Within your footer will be copyright, legal and contact information primarily. It's a good idea to include a few links to the most important sections of your site such as the top of the page, home page, contact page, etc. Some websites use this area as an opportunity to mention related material or other important information.
This is any area of the web page that is not covered by typography or other content. You may feel the strong urge to fill as much empty space as possible but don't do it! Empty space is just as important to a good web page design as the content to be used. You can see how the NetTuts site uses empty space very effectively to help guide visitors through content, create page balance and give a good sense of content separation.
So that covers the anatomy of a web page. Now lets take a look at how the Golden Ratio relates to these elements.
Advertisement
Remember earlier when I said math was beautiful? We perceive visual appeal based on ratio (i.e. The Golden Ratio). For thousands of years artists, designers, architects, etc. have either intentionally or unintentionally used a common ratio in their work that is aesthetically pleasing. What is the magic number? 1.62 (actually 1.618...) I won't get into the origins of this number but I will tell you how to use it.

Using the golden ratio is very simple. Lets say you want to find the width of your Main Content and Sidebar columns. You would take the total width of your content area (we'll use 900px for this example) and divide that by 1.62. As shown in the example above we divide 900px by 1.62 and get 555.55px. We don't need to be exact so we will round it off to 555px. Now you know your main content element will be 555px wide and your sidebar will be 345px! How easy is that?!
But wait! The fun doesn't stop there. You can also apply the Golden Ratio to other element's width in relation to its height or vice-versa. This produces aesthetically pleasing elements with the Golden Ratio proportions.

If you're like most people though, you won't want to pull out a calculator every time you want to use this ratio. To simplify the process, we can use a simple grid. All you do is divide your width and/or height by thirds.

Each division can be even further reduced by thirds, producing a more detailed grid. If you read the previous article "A Close Look At the Blueprint CSS Framework" you will see that the Blueprint CSS framework uses a detailed grid system. Not only does the grid make designing easier and faster but also it creates an aesthetically pleasing layout! If you aren't already using a grid when designing, now may be a good time to give it a try. You can download a grid template for fireworks, photoshop and more from http://960.gs, which is another fantastic CSS framework that uses grids.

As you can see, Tuts+ abides by the Golden Ratio quite well. The top one third of the page is divided again into thirds to show how even the header section breaks down into smaller increments of thirds, very close to the Golden Ratio. No wonder why the NetTuts design is so appealing!
If you're new to design I highly encourage you to find some popular sites, evaluate their element layout and how it abides by the Golden Ratio and grids. Then take some time to practice using the Golden Ratio with your elements and placing them in your layout using a grid.

How to Add Branded Branch Locations to Google Maps

by

Final product image
What You'll Be Creating

The Plan

In this tutorial we'll walk through the process of creating a branded Google map for an imaginary client. Our map will include three key features:
  1. Custom markers at each of the client's branch locations
  2. The client's logo in a fixed position on the map
  3. Map theming which compliments the client's branding
In this case, our imaginary client is going to be "The Hobby Shoppe", purveyors of fine board games and other hobby paraphernalia around the city of Melbourne, Australia.

Creating the Base Map

We'll get the ball rolling by creating a basic map centered on the city of Melbourne. After we add our branch markers we'll refine the center position of the map, but for now we'll start by finding the right latitude and longitude in order to show the city as a whole.

Initial Latitude and Longitude

To do this go to Google Maps and search for Melbourne, then zoom in just a little so you're not including unpopulated areas. As you adjust the position of the map you'll notice the URL changes to reflect your new latitude, longitude and zoom level. When you have the map positioned where you like, copy the URL somewhere for later reference, e.g:
https://www.google.com/maps/place/Melbourne+VIC/@-37.804627...
After the @ symbol in the URL you'll see comma separated values for the latitude, longitude and zoom level: -37.8046274,144.972156,12z
The first value -37.8046274 is the latitude, the second value 144.972156 is the longitude, and the 12z value means the zoom level is set to 12. We're now going to plug these values into a basic map.

Basic Markup

Create a blank HTML document and add the following code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      .wrap { max-width: 75em; min-height: 40em; height:100%; width:100%; margin: 0 auto; padding-top: 2.5%;}
      #map-canvas { height: 90%; }
    </style>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true">
    </script>
    <script type="text/javascript">
      var map;
      var centerPos = new google.maps.LatLng(-37.8046274,144.972156);
      var zoomLevel = 12;
      function initialize() {
        var mapOptions = {
          center: centerPos,
          zoom: zoomLevel
        };
        map = new google.maps.Map( document.getElementById("map-canvas"), mapOptions );
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
  <div class="wrap">
    <div id="map-canvas"></div>
  </div>
  </body>
</html>
With this markup we have created an HTML document including a div with the id map-canvas which will hold our map. We've also added some basic CSS to size and position the map-canvas div.
Lastly, we've loaded the required script from the Google Map API with:
1
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
and we've created a JavaScript function to set the basic options of the map and load it into our empty div.
01
02
03
04
05
06
07
08
09
10
11
12
13
<script type="text/javascript">
  var map;
  var centerPos = new google.maps.LatLng(-37.8046274,144.972156);
  var zoomLevel = 12;
  function initialize() {
    var mapOptions = {
      center: centerPos,
      zoom: zoomLevel
    };
    map = new google.maps.Map( document.getElementById("map-canvas"), mapOptions );
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>
Note: see how the values we took from the Google Maps URL earlier have been used in the centerPos and zoomLevel variables, which are in turn used in the mapOptions array. The centerPos variable uses the comma separated latitude and longitude values of -37.8046274,144.972156, and the zoomLevel variable uses the value of 12.
Save your HTML file and open it up in any browser. Your base map should look a bit like this:

Adding Branch Location Markers

The next step is to find the latitude and longitude for each of the client's branch locations, so we can create markers for them at those positions. The easiest way to do this is to find each branch address via a Google Maps search and grab the latitude and longitude from there.

Find Latitude and Longitude of Each Branch

Head back to Google Maps again and run a search for each branch location. Assuming the client has given you the addresses of each location, you can simply search for that address and a marker will appear on the map. Right click that marker and choose What's here? from the context menu.
A small popup will appear at the top left of the map displaying details for this marker including latitude and longitude:

Add Locations to the Initialize Function

Make a note of the latitude and longitude for each of the branch locations you want to add to your map. In the case of "The Hobby Shoppe" we have seven branch locations and we'll add markers for each by inserting the following code just before the end of our map's initialize() function, after the map = new google.maps.Map... line:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
var locations = [
  ['First Shoppe', -37.808204, 144.855579],
  ['Second Shoppe', -37.675648, 145.026125],
  ['Third Shoppe', -37.816935, 144.966877],
  ['Fourth Shoppe', -37.818714, 145.036494],
  ['Fifth Shoppe', -37.793834, 144.987018],
  ['Sixth Shoppe', -37.737116, 144.998581],
  ['Seventh Shoppe', -37.765528, 144.922624]
];
 
for (i = 0; i < locations.length; i++) { 
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    title: locations[i][0],
    map: map
  });
}
In this code we are first creating an array of branch locations with the name, latitude and longitude of each. We're then iterating through that array to add each location as a marker to the map, with the title to be displayed as a tool tip if the marker is hovered over.
Your map should now have markers added like so:
But wait, there's something wrong with this picture. We added seven locations, and yet only six markers appear. Why?
It's simply because our seventh marker is just out of view based on the initial latitude and longitude we set for the map, so we need to refine that center position.

Adjusting the Map Center Position

Now that we have all our markers in place we can refine the starting position of the map to ensure they're all visible on load. To do that we'll add a button which we can click to give us new co-ordinates once we find the perfect map starting position.
Add this button code to your page, anywhere in the body section:
1
<button onclick="console.log( 'Lat &amp; Long: ' + map.getCenter().k + ',' + map.getCenter().A + ' Zoom: ' + map.getZoom() );">Get Map Co-ords</button>
Now you can move your map around and then click the new Get Map Co-ords button when you find the right spot.
The latitude, longitude and zoom level of your position will be written to your console, so make sure you have the Chrome Dev Tools or Firebug console open.
Update your map's center option with the new latitude and longitude, as well as the zoom option if that has changed too:
1
2
3
4
var mapOptions = {
  center: new google.maps.LatLng(-37.74723337588968,144.961341333252),
  zoom: 12
};
Save and refresh your map and now all seven map markers should be visible. When you're happy with the refined center position you can remove the Get Map Co-ords button code.

Adding Custom Marker Images

Now that we have all the markers in place and visible for the branch locations we're going to convert them into a custom image, one that goes with the client branding and the style of map. Any image created for use as a map marker should have a transparent background, e.g.
Place your custom marker in an "images" folder, relative to the folder your base map is in, then add the following variable directly under the locations variable you created previously:
1
var image = 'images/shoppe_icon.png';
Then add an extra option of icon: image to the for loop we created earlier to place map markers. Passing this variable into the map marker generation options specifies that you want the marker icons to be replaced with your custom image:
1
2
3
4
5
6
7
8
for (i = 0; i < locations.length; i++) { 
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    title: locations[i][0],
    map: map,
    icon: image
  });
}
Take another look at your map and you should now see little houses at each of the seven branch locations:

Adding the Client's Logo

We're now going to add the client's logo in such a way that it will remain the same size and in the same position regardless of where the map is zoomed or panned to.
The only elements of a Google Map that don't move with panning and zooming are the control UI elements, typically used for things like engaging street view or switching map types. However, we can use the custom control API equally well to place a logo on the screen. We'll also have our new custom control reset the zoom and center position of the map when clicked so as well as displaying the logo it performs a useful UI function.
Start by adding your client's logo image into the same "images" folder you placed your custom marker image. Then add the following JavaScript function just before your existing initialize() function:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
function LogoControl(controlDiv, map) {
 
  controlDiv.style.padding = '5px';
 
  var controlUI = document.createElement('div');
  controlUI.style.backgroundImage = 'url(images/logo.png)';
  controlUI.style.width = '600px';
  controlUI.style.height = '116px';
  controlUI.style.cursor = 'pointer';
  controlUI.title = 'Click to set the map to Home';
  controlDiv.appendChild(controlUI);
 
  google.maps.event.addDomListener(controlUI, 'click', function() {
    map.setCenter(centerPos)
    map.setZoom(zoomLevel)
  });
 
}
When executed, this function will create a control UI element 600px by 116px in size, using the logo image as its background. It will also create a listener which will reset the center and zoom of the map if the logo is clicked.
Then, at the end of your initialize() function, insert the following code:
1
2
3
4
5
var logoControlDiv = document.createElement('div');
var logoControl = new LogoControl(logoControlDiv, map);
 
logoControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_CENTER].push(logoControlDiv);
When the initialize() function runs it will now call the LogoControl() function we just created and add its output into the map controls.
Your map should now look like this:

Coloring the Map

To setup the colors of your map you'll almost certainly want to use Google's Styled Map Wizard in order to get rapid visual feedback on your choices.
The Feature type menu in the wizard gives you a range of map components available for styling. They're organized from the most general, down to most specific. At the most general level you can apply color choices to the All feature type, in order to affect everything on the map equally. On the other end of the spectrum you can drill down as specifically as All > Transit > Station > Bus for example.
With a Feature type selected you can then also make a selection from the Element type menu to determine if you want your color choices to influence the feature's geometry or its labels (such as the little text labels you see floating around the map). Furthermore, you can then also select either the fill or stroke color to modify.
When it comes to choosing colors there are two main areas you'll want to work with; the Colour panel and the Hue panel. The Colour panel will apply a color hexcode flatly to the features and elements you have selected, whereas the Hue panel will tint your selection with a range of lightness and darkness influenced by each element's original color.
As a general rule you should start by applying a Hue to the most general levels of your map so you have some uniformity in your color scheme - you could compare this to a base coat of paint. From there you can then drill down to "paint" over the top with flat Colour settings for more specific features and elements.

Our Map

Start by searching in the wizard for "Melbourne" and then positioning the preview map to show you approximately the same area you set your own map to show.
Under the Feature type menu in the wizard select All, and under the Element type menu select Geometry. Then check the Hue box and click the color bar until you get a value of somewhere around #ffa200. For some reason you can't directly enter a value in this field, so you have to get it as close as you can by clicking. Then check the Invert lightness box, activate the Saturation setting and drag it to 35, activate the Lightness setting and place it at 50, and activate the Gamma setting and get it as close as you can to 1.3.
These settings should have tinted your entire map like so:
Your map looks a little funny at this stage because we're aiming to make a colorful map, so the tint settings here have been amped up to ensure there are no drab areas anywhere. The excessively bright areas will be overridden with more subdued colors in subsequent steps.

Toning Things Down

Now that you have your first style applied, click the Add button in the top right corner of the Map Style panel, (located at the right side of the map wizard). Clicking this button creates a second style named "Style 1" under which you can select different elements and apply new styles.
With "Style 1" selected in the Map Style panel and All still selected under Feature type click the Labels option in the second list of the Element type menu. Check the Hue box and again set it to a value of #ffa200 so your labels are all tinted instead of being bright blue or green as you see in the image above.
Click the Add button on the Map Style panel to create another new style, then click Water in the second list of the Feature type menu. Under the Element type menu select Geometry. Check the Color box and enter a color hexcode of #8F9B98.

The Remaining Styles

You should now know how to create new styles, by selecting Feature type and Element type menu items. Go ahead and add the rest of these styles one at a time in the styled map wizard:
  • Feature type: All
  • Element type: All > Labels > Text > Fill
  • Color: #f8ead0
  • Feature type: All
  • Element type: All > Labels > Text > Stroke
  • Color: #6a5035
  • Feature type: All > Landscape > Man made
  • Element type: All > Geometry
  • Color: #9f8053
  • Feature type: All > Landscape > Natural
  • Element type: All > Geometry
  • Color: #9c9743
  • Feature type: All > Point of interest
  • Element type: All > Geometry
  • Color: #ACA74C
  • Feature type: All > Road
  • Element type: All > Geometry > Fill
  • Color: #d3b681
  • Feature type: All > Road
  • Element type: All > Geometry > Stroke
  • Color: #644F34
  • Feature type: All > Road > Arterial
  • Element type: All > Geometry > Fill
  • Color: #c6a15e
  • Feature type: All > Road > Local
  • Element type: All > Geometry > Fill
  • Color: #b09061
  • Feature type: All
  • Element type: All > Labels > Text > Stroke
  • Color: #483521
  • Feature type: All > Transit > Line
  • Element type: All > Geometry
  • Color: #876b48
  • Feature type: All > Transit > Station
  • Element type: All > Geometry
  • Color: #a58557
Advertisement

Exporting Map Styles

Once you've added all these styles you're ready to export the settings the wizard has created and add them into your map. On the Map Style panel click the Show JSON button at the bottom. You'll see a white window appear, displaying an array of JavaScript options.
Copy all the text from that window between the opening [ and closing ], i.e. everything but the main heading.
At the beginning of your initialize() function add this new line:
1
var styles = ;
Position your cursor before the ; then paste in the code you copied from the styled map wizard. You should end up with:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
var styles = [
  {
    "elementType": "geometry",
    "stylers": [
      { "hue": "#ffa200" },
      { "invert_lightness": true },
      { "lightness": 50 },
      { "saturation": 35 },
      { "gamma": 1.31 }
    ]
  },{
    "elementType": "labels",
    "stylers": [
      { "hue": "#ffa200" }
    ]
  },{
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [
      { "color": "#8F9B98" }
    ]
  },{
    "elementType": "labels.text.fill",
    "stylers": [
      { "color": "#f8ead0" }
    ]
  },{
    "elementType": "labels.text.stroke",
    "stylers": [
      { "color": "#6a5035" }
    ]
  },{
    "featureType": "landscape.natural",
    "elementType": "geometry",
    "stylers": [
      { "color": "#9c9743" }
    ]
  },{
    "featureType": "landscape.man_made",
    "elementType": "geometry",
    "stylers": [
      { "color": "#9f8053" }
    ]
  },{
    "featureType": "poi",
    "elementType": "geometry",
    "stylers": [
      { "color": "#ACA74C" }
    ]
  },{
    "featureType": "road",
    "elementType": "geometry.fill",
    "stylers": [
      { "color": "#d3b681" }
    ]
  },{
    "featureType": "road",
    "elementType": "geometry.stroke",
    "stylers": [
      { "color": "#644F34" }
    ]
  },{
    "featureType": "road.arterial",
    "elementType": "geometry.fill",
    "stylers": [
      { "color": "#c6a15e" }
    ]
  },{
    "featureType": "road.local",
    "elementType": "geometry.fill",
    "stylers": [
      { "color": "#b09061" }
    ]
  },{
    "featureType": "transit.line",
    "elementType": "geometry",
    "stylers": [
      { "color": "#876b48" }
    ]
  },{
    "featureType": "transit.station",
    "elementType": "geometry",
    "stylers": [
      { "color": "#a58557" }
    ]
  }
];
Then at the very end of the initialize() function add these three lines:
1
2
3
var styledMap = new google.maps.StyledMapType( styles, {name: "Styled Map"} );
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
These lines of code apply all the color scheme data you just pulled in from the styled map wizard to your map. Take another look and it should now appear with all your styling selections in place:
Check out the live demo so you can see the map at its proper size and play around with zooming and panning here.

Wrapping Up

As a final touch you might also like to add a frame effect around your map to further compliment the styling. Replace the existing #map-canvas { ... } CSS in your file with this:
1
2
3
4
5
6
7
#map-canvas {
  height: 90%;
  border: 5px solid #33210f;
  -moz-box-shadow: 0 3px 3px 3px rgba(0,0,0,0.9), 0 0 0 3px #000;
  -webkit-box-shadow: 0 3px 3px 3px rgba(0,0,0,0.9), 0 0 0 3px #000;
  box-shadow: 0 3px 3px 3px rgba(0,0,0,0.9), 0 0 0 3px #000;
}
As you can see, there's quite a lot you can do with Google Maps beyond just basic embedding. In this tutorial we've still only explored a couple of aspects of the Google Maps API - you can read more about all the other functions offered by the API in the Google Map help docs.
If you want to take this tutorial even further you could also try adding your own custom styled zoom and pan controls (custom control docs), and creating info windows which pop up when markers are clicked . These popups could hold details like phone number and street address (info windows docs).
Give these techniques a try next time a client asks you to include a Google Map in their site. You might just get a bonus!

Build a Dynamic Grid with Salvattore and Bootstrap in 10 Minutes

by

Salvattore touts itself as a jQuery Masonry alternative with one important difference: it uses CSS configuration instead of JavaScript. These kinds of grids can be seen all over the web, probably most famously on Pinterest.
Today, we will use Salvattore in combination with Twitter Bootstrap 3 to make a responsively awesome flowing grid structure.

Getting started: What You'll Need

First, you'll need to grab the Salvattore JavaScript library (minified or source). Next, you'll want to link up Twitter Bootstrap's CSS. Instead of downloading and hosting our own copy, we'll borrow this directly from NetDNA's BootstrapCDN.
01
02
03
04
05
06
07
08
09
10
11
12
13
<html>
    <head>
        <link rel="stylesheet" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
        <title>Salvattore + Bootstrap</title>
    </head>
    <body>
     
    <!-- This is where the magic happens! -->
     
    <script src="salvattore.js"></script>
     
    </body>
</html>
Once this is complete, you're ready to get started with configuring Salvattore!
Next, you'll need either an external stylesheet or a <style type='text/css'> tag in your header. Most of our work will be done in the stylesheet.
Note: you must include type and rel attributes for Salvattore to work properly.

A Quick Bootstrap Grid Primer

Twitter Bootstrap provides a powerful, flexible grid structure which focuses on bottom-up media queries. Let's take a look at a common row of columns.
1
2
3
4
5
6
7
8
<div class="row">
    <div class="col-xs-12 col-md-4"></div>
    <div class="col-xs-6 col-sm-3 col-md-4"></div>
    <div class="col-xs-6 col-sm-3 col-md-4"></div>
    <div class="col-xs-12 col-sm-3 col-md-4"></div>
    <div class="col-xs-6 col-md-4"></div>
    <div class="col-xs-6 col-md-4"></div>
</div>
You'll notice in the above markup the pattern of col-[size]-[column number]. With available sizes of xssm,md, and lg, we are able to set different column sizes for different breakpoints without writing specific media queries. Take a look at this example which shows how the columns shift at different screen widths.

Bootstrap Panels

We will be creating a flowing grid using Bootstrap's panel component. The markup to create the panel is built like this:
1
2
3
4
<div class="panel panel-primary">
    <div class="panel-heading">Panel heading without title</div>
    <div class="panel-body">Panel content</div>
</div>

Putting it Together with Salvattore Magic

Now that we have the Bootstrap pieces we need, we're going to put it all together with Salvattore. For now, we'll start with six empty panels; later, we will make it all dynamic to give each panel some content.
For Salvattore to work properly, our grid container needs a data-columns attribute. Here is what our markup currently looks like:
1
2
3
4
5
6
7
8
9
<div id="grid" data-columns>
    <div class="panel panel-primary">
        <div class="panel-heading">Panel heading without title</div>
        <div class="panel-body"> Panel content </div>
    </div>
     
    <!-- repeat the panel as many times as you'd like -->
     
</div>
Next, we will go to our stylesheet and add the following labels via pseudo-elements:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
@media screen and (min-width: 1px) and (max-width: 767px){
    #columns[data-columns]::before {
        content: '2 .col-xs-6';
    }
}
@media screen and (min-width:768px) and (max-width: 991px){
    #columns[data-columns]::before {
        content: '3 .col-sm-4';
    }
}
@media screen and (min-width:992px) and (max-width: 9999px){
    #columns[data-columns]::before {
        content: '4 .col-md-3';
    }
}
The breakpoints we've chosen map directly to Bootstrap's media queries. Salvattore uses the::before pseudo-element and content attribute to define the classes of the columns created, and then attempts to split the elements evenly into those columns.

Making it Dynamic

We've kept thing strictly within CSS so far, but if you'd like to go the extra mile, JavaScript can offer a few goodies.
Salvattore takes things a step further by offering appending functionality. With these functions and a connection to an API (we're using Google's Book API to pull in books by Ernest Hemingway), we can build a dynamic grid. Here's the JavaScript we'll use:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
function append(title, content) {
    // build/select our elements
    var grid = $('#columns')[0];
    var item = document.createElement('div');
    // build the html
    var h = '<div class="panel panel-primary">';
    h += '<div class="panel-heading">';
    h += title;
    h += '</div>';
    h += '<div class="panel-body">';
    h += content;
    h += '</div>';
    h += '</div>';
    salvattore['append_elements'](grid, [item])
    item.outerHTML = h;
}
$.getJSON("https://www.googleapis.com/books/v1/volumes?q=inauthor:Ernest+Hemingway&callback=?", function (data) {
    $(data.items).each(function (i, book) {
        append(book.volumeInfo.title, book.volumeInfo.description);
    });
});
Note:  jQuery Required
First we create an append function which takes our title and content, and wraps them in our panel markup. We then use the salvattore['append_elements'](grid, [item]) function to add the item to our grid. Finally, we run the AJAX call to pull in the dynamic data.
For this to work properly, we'll want to remove all of the contents in the grid holder.
1
<div id="grid" data-columns></div>
Salvattore will fill in the columns for us.
Our final markup looks like this:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!DOCTYPE html>
 
<html>
<head>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        @media screen and min-width 1px and max-width 767px {
            #columns[data-columns]::before {
                content: '2 .col-xs-6';
            }
         
        }
         
        @media screen and min-width768px and max-width 991px {
            #columns[data-columns]::before {
                content: '3 .col-sm-4';
            }
         
        }
         
        @media screen and min-width992px and max-width 9999px {
            #columns[data-columns]::before {
                content: '4 .col-md-3';
            }
         
        }      
    </style>
 
    <title></title>
</head>
 
<body>
    <div class="container">
        <h1 class="col-xs-12">Books by Ernest Hemingway</h1>
 
        <div data-columns="" id="columns">
            <div></div>
            <div></div>
            <div></div>         
        </div>
    </div>
     
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="salvattore.js"></script>
    <script>
        function append(title, content) {
            var grid = document.querySelector('#columns');
            var item = document.createElement('div');
            var h = '<div class="panel panel-primary">';
            h += '<div class="panel-heading">';
            h += title;
            h += '</div>';
            h += '<div class="panel-body">';
            h += content;
            h += '</div>';
            h += '</div>';
            salvattore['append_elements'](grid, [item]) item.outerHTML = h;
        }
        $.getJSON("https://www.googleapis.com/books/v1/volumes?q=inauthor:Ernest+Hemingway&callback=?", function (data) {
            $(data.items).each(function (i, book) {
                append(book.volumeInfo.title, book.volumeInfo.description);
            });
        });
    </script>
</body>
</html>

Conclusion

Salvattore makes creating dynamic Masonry-style grids very easy for someone who doesn't know a lot of JavaScript. Saying that, with a small amount of JavaScript, creating dynamic grids coupled with dynamic content is a breeze. Lastly, Bootstrap provides flexible class naming structure to easily construct grids for any breakpoint.

 

Copyright @ 2013 Krobknea.

Designed by Next Learn | My partner