Рабочие заметки вебмастера

Умные колонки при помощи CSS и jQuery

При просмотре различных резиновых сайтов, я увидел два основных способа отображения колонок — фиксированные и резиновые.

Фиксированные колонки

Фиксированные колонки

Фиксированные колонки

Резиновые колонки

Резиновые колонки

Резиновые колонки

Умные колонки при помощи CSS и jQuery

Данный способ позволяет исправить недостатки обоих вариантов представленных выше. Можно использовать любое количество колонок. Строка всегда будет заполнена на 100% без лишних пробелов. При помощи jQuery мы определяем ширину строки, потом высчитываем количество помещающихся колонок. Если колонки заполняют не всю строку, скрипт равномерно добавляет оставшуюся не используемую ширину колонкам. HTML:

<ul class="column"> <!--Repeating list item-->
	<li><div class="block"><!--Content--></div></li>
</ul><!--end repeating list item-->

CSS:

ul.column {
	width: 100%;
	padding: 0;
	margin: 10px 0;
	list-style: none;}
	ul.column li {
		float: left;
		width: 200px; /*Set default width*/
		padding: 0;
		margin: 5px 0;
		display: inline;}
.block {
	height: 355px;
	font-size: 1em;
	margin-right: 10px; /*Creates the 10px gap between each column*/
	padding: 20px;
	background: #e3e1d5;}
	.block h2 {font-size: 1.8em;}
	.block img {
		/*Flexible image size with border*/
		width: 89%;  /*Took 1% off of the width to prevent IE6 bug*/
		padding: 5%;
		background:#fff;
		margin: 0 auto;
		display: block;
		-ms-interpolation-mode: bicubic; /*prevents image pixelation for IE 6/7 */}

jQuery:

function smartColumns() { //Create a function that calculates the smart columns

	//Reset column size to a 100% once view port has been adjusted
	$("ul.column").css({ 'width' : "100%"});

	var colWrap = $("ul.column").width(); //Get the width of row
	var colNum = Math.floor(colWrap / 200); //Find how many columns of 200px can fit per row / then round it down to a whole number
	var colFixed = Math.floor(colWrap / colNum); //Get the width of the row and divide it by the number of columns it can fit / then round it down to a whole number. This value will be the exact width of the re-adjusted column

	$("ul.column").css({ 'width' : colWrap}); //Set exact width of row in pixels instead of using % - Prevents cross-browser bugs that appear in certain view port resolutions.
	$("ul.column li").css({ 'width' : colFixed}); //Set exact width of the re-adjusted column

}

smartColumns();//Execute the function when page loads

$(window).resize(function () { //Each time the viewport is adjusted/resized, execute the function
	smartColumns();
});

Пример

Оригинал статьи — Torrance Website Design — Soh Tanaka: Smart Columns w/ CSS & jQuery