Home » Articles » Generating hex grids - part 1

Generating hex grids - part 1

Sun May 7, 2017

Lately I’ve been reading a lot into generating hex grids for my game engine, Civitas. Generating hex grids is usually done in turn-based strategy games, similar to Sid Meier’s Civilization series or Heroes of Might and Magic series of video games.

Below is a 10x7-cell hex grid generated with HTML, CSS and Javascript that can be further enhanced by attaching coordonates. If you want to generate HTML5 canvas grids, you might want to look into Hexagon.js library or even Fabric.js.


The HTML code is simple, just a container div that holds all the cells.
<div id="grid" class="grid"></div>

Here is the CSS code that controls the style of the cells and their container.

.grid {
	width: 670px; 
	line-height: 1.3;
	height: 410px;
	background-color: #666;
}
.grid ol {
	margin-left: 20px;
	padding: 0;
}
.grid ol.even {
	position: relative;
	left: 1.95em;
}
.grid ol.odd {
	position: relative;
	margin-top: -8.6%;
	margin-bottom: -6.2%;
}
.grid .cell {
	position: relative;
	margin: 1em auto;
	width: 2em;
	height: 3.6em;
	-webkit-border-radius: 20em/1em;
	-moz-border-radius: 20em/1em;
	border-radius: 20em/1em;
	background: transparent;
	-webkit-transform: rotate(-90deg);
	-moz-transform: rotate(-90deg);
	transform: rotate(-90deg);
	display: inline-block;
	margin-right: 1.94em;
}
.grid .cell:before,
.grid .cell:after {
	position: absolute;
	width: inherit;
	height: inherit;
	background: inherit;
	content: '';
}
.grid .cell:before {
	-webkit-transform: rotate(60deg);
	-moz-transform: rotate(60deg);
	transform: rotate(60deg);
}
.grid .cell:after {
	-webkit-transform: rotate(-60deg);
	-moz-transform: rotate(-60deg);
	transform: rotate(-60deg);
}
.grid .cell.empty {
	background-color: #ddd;
}
.grid .cell:hover {
	background-color: #ff0000;
}

And the Javascript code that builds the actual grid inside the container, by alternating ol lists for the even/odd effect:

var mode = 'even';
var template = '';
for (var y = 0; y <= 6; y++) {
	template += '<ol class="' + mode + '">';
	for (var x = 0; x <= 9; x++) {
		template += '<li data-x="' + x + '" data-y="' + y + '" class="cell empty"></li>';
	}
	template += '</ol>';
	mode = (mode === 'even') ? 'odd' : 'even';
}
document.getElementById('grid').innerHTML = template;

As you can see, I’ve attached two data- (data-x and data-y) attributes to each cell so they can be referenced via their positioning in the grid. But that in the next articles in the series.


  « Previous: Next: »