RyoSugimoto
4/21/2014 - 10:16 AM

CSSのcalc()関数が使えなくても、左右幅にぴったりの可変幅カラムレイアウトを実現する。

CSSのcalc()関数が使えなくても、左右幅にぴったりの可変幅カラムレイアウトを実現する。

<div class="container">

	<div class="parent" style="overflow: hidden;">
		
		<div class="child" style="background: #CCC; float: left; margin-right: 10px;">
			Element
		</div>
		<div class="child" style="background: #CCC; float: left; margin-right: 10px;">
			Element
		</div>

	</div>

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="cssCalc.js"></script>
<script src="fitColumns.js"></script>
<script>
$(function () {
	$('.parent').fitColumns({
		gutter: 10,
		cols: 2
	});
});
</script>
;(function (window, $, undefined) {
	$.fn.fitColumns = function (options) {
		options = $.extend({}, {
			cols: 3,
			gutter: 10,
			containerClass: 'fit-columns-container'
		}, options);
		return this.each(function () {
			var $row = $(this),
				$columns = $row.children();
			$row
				.cssCalc('width', '100% + ' + options.gutter + 'px')
				.css('margin-right', - options.gutter + 'px');
			$columns
				.cssCalc('width',
				'( (100% - ' + options.gutter + ') - (' + options.cols + ' - 1) * ' + options.gutter + ') / ' + options.cols)
				.css('margin-right', options.gutter + 'px');
		});
	};
}(window, jQuery));
;(function (window, $, undefined) {

	$.fn.cssCalc = function (prop, val, callback) {

		var $window = $(window),
			$html = $('html');

		if (typeof callback !== 'function') {
			callback = function (elm) {
				$.noop();
			};
		}

		return this.each(function () {

			var $this = $(this),
				$parent = $this.parent();

			setSize($this, val, $parent);

			$window.on('resize', function () {
				setSize($this, val, $parent);
			});

		});

		function getSize ($elm) {
			return {
				width: $elm.width(),
				height: $elm.height()
			};
		}

		function getFontSize ($elm) {
			return $elm.css('font-size');
		}

		function calcUnit (val, $parent) {
			var f = val.replace(/(\d+)%/g, getSize($parent)[prop] + ' * ($1 / 100)'),
				f = f.replace(/(\d+)em/g, getFontSize($parent) + ' * $1'),
				f = f.replace(/(\d+)rem/g, getFontSize($html) + ' * $1'),
				f = f.replace(/px/g, '');
			return eval(f);
		}

		function setSize ($this, val, $parent) {
			var size = Math.floor(calcUnit(val, $parent));
			$this.css(prop, size + 'px');
			callback($this[0]);
		}

	};

}(window, jQuery));