Flexible horizontal sidebars in WordPress (using Twenty Thirteen child theme)

Flexible is good, at least when it comes to websites. After all, responsive has been THE buzzword of all buzzwords for quite some time. Using media queries, you can make a three column layout switch to two columns, than one, depending on width of device website is being displayed on. But what about setting number of columns based on content? Easy, using WordPress widget areas.

I’ll use Twenty Thirteen child theme in this example. If you don’t know how to create a WordPress child theme, read that post at ThematoSoup. Twenty Thirteen uses Masonry to display widgets in its main widget area (footer). In order to switch to grid based layout, you need to dequeue Masonry script first:

// Removes Masonry enqueued by Twenty Thirteen to handle vertical alignment of footer widgets.
function slbd_dequeue_masonry() {
   wp_dequeue_script( 'jquery-masonry' );
}
add_action( 'wp_print_scripts', 'slbd_dequeue_masonry' );

Once that’s been done, let’s create a helper function that will return a few classes to add to div.widget-area (comments inline):

And use the function in footer.php file, copied from child theme’s sidebar-main.php, copied from parent theme’s folder:

<?php
/**
 * The sidebar containing the footer widget area.
 */

if ( is_active_sidebar( 'sidebar-1' ) ) : ?>
	<div id="secondary" class="sidebar-container" role="complementary">
		<div class="widget-area flexible-widget-area <?php echo slbd_count_widgets( 'sidebar-1' ); ?>">
			<?php dynamic_sidebar( 'sidebar-1' ); ?>
		</div><!-- .widget-area -->
	</div<>!-- #secondary -->
<?php endif; ?>

Now it’s easy set number of widgets shown per row, by using .per-row-2, .per-row-3 and .per-row-4 classes that were added to widget area:

/* Two per row */
.flexible-widget-area.per-row-2 .widget {
    width: 50%;
}
/* Three per row */
.flexible-widget-area.per-row-3 .widget {
    width: 33.33333%;
}
/* Four per row */
.flexible-widget-area.per-row-4 .widget {
    width: 25%;
}

And here’s full CSS file:


What you get as result will look like this:

Four widgets per row

Four widgets per row

Three widgets per row

Three widgets per row

Two widgets per row

Two widgets per row

You can also download the child theme. Let me know how you think this technique could be improved.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>