Яндекс.Метрика

Дизайн-журнал №1. Актуальная информация для дизайнеров, веб дизайнеров, программистов и разработчиков сайтов.

Несколько колонок при помощи css3

11 июля 2012 | Опубликовано в css | 3 Комментариев »

Наверное, у многих возникала необходимость создания контейнера с несколькими колонками для отображения нужной информации, где текст выглядит приблизительно так, как столбцы в газетах. И многие, скорее всего, реализовали это при помощи обычных div-ов или других элементов и свойства float: left. Css3 даёт нам новые удивительные возможности. Вам не нужно будет делить текст на блоки, теперь всё это можно сделать при помощи простых правил.

 

В нашем уроке мы будем использовать новые свойства css3:

Чтобы лучше понять, как эти свойства работают, рекомендуем прочесть эту статью.

Результат

Смотрите демо

Давайте приступим к работе!

Шаг 1. HTML

Вот так выглядит наша html-разметка. Обратите внимание, что здесь только один <div> для текста.

<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <title>Multi-columns with CSS3 | Script Tutorials</title>
        <link href="css/main.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="js/jquery-1.5.2.min.js"></script>
        <script type="text/javascript" src="js/script.js"></script>
    </head>
    <body>
        <div class="controls">
            <input type="button" id="more_cols" value="More columns" />
            <input type="button" id="less_cols" value="Less columns" />
            <input type="button" id="more_gap" value="More gap" />
            <input type="button" id="less_gap" value="Less gap" />
        </div>

        <div class="container" id="container">
            <p>The King sat naked. Like a foolish pauper on the street, he sat leaning
            against  a  cold  wall, drawing in his blue, goose-bumped legs. He shivered,
            with his eyes closed, he listened, but everything was quiet.</p>
            <p>He awoke at midnight from a nightmare and immediatelly understood  that
            he  was  finished.  Some  one  weezed and writhed by the door of the bedroom
            suite, he heard footsteps, metalic jingling and  drunken  mummbling  of  His
            Highness,  Uncle  Buht: "Let me through... Let me.. Break it down, hell with
            it..." Wet with icy sweat, he slintly rolled off  his  bed,  ducked  into  a
            secter  closet,  and  loosing  himself  he ran down the underground passage.
            Something sqelched under his bare feet, the startled rats dashed  away,  but
            he  did  not notice anything, just now, sitting next to a wall he remembered
            everything; the darkness, the slippery walls, and the pain from  a  blow  on
            the  head against the shakled door to the temple, and his own unberable high
            yelp.</p>

            <p>They shall not enter here, he thought. No one shall enter here. Only if
            the King  order's  so.  But  the  King  shall  not  order...  He   snickered
            hysterically. Oh no, the King will not order! He carefully un screwed up his
            eyes  and  saw  his  blue, hairless legs with scraped knees. Still alive, he
            thought. I will live, because they shall not enter here.</p>
            <p>Everything in the temple  was  blueish  from  the  cold  light  of  the
            lanterns -- long glowing tubes that were stretched under the ceiling. In the
            center,  God stood on an eminence, big, heavy, with sparkling dead eyes. The
            King continuously and stupidly stared, until God was suddenly screened by  a
            shabby  lay  brother,  still  a  greenhorn. Scraching, with an open mouth he
            gazed at the naked King. The King squinted once again. Scum, he  thought,  a
            lousy  vermine,  catch the mongrel and to the dogs, for them to ravage... He
            reasoned that he did not remember the lout well, but he was  long  gone.  So
            scrawny,   snotty...   That's  all  right,  we'll  remember.  We'll  remeber
            everything, Your Highness, Uncle Buht. During the father's  reighn,  I  dare
            say you sat quietly, drank a bit and kept silent, were afraid to be noticed,
            you knew that King Prostyaga did not forget you ignoble treachery...</p>
        </div>
        <footer>
            <h2>Multi-columns with CSS3</h2>
            <a href="http://www.script-tutorials.com/how-to-do-multi-columns-with-css3/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
        </footer>
    </body>
</html> 

Шаг 2. CSS

А теперь добавим стили

*{
    margin:0;
    padding:0;
}

body {
    background-color:#bababa;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

/*new styles*/
.container {
    background:#C5DFF0;
    color:#000;
    margin:20px auto;
    padding:20px;
    position:relative;
    width:800px;

    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;

    box-shadow:1px 1px 5px #111111;

    column-count: 3;
    column-gap: 3em;
    column-rule: 1px dashed black;
    -moz-column-count: 3;
    -moz-column-gap: 3em;
    -moz-column-rule: 1px dashed black;
    -webkit-column-count: 3;
    -webkit-column-gap: 3em;
    -webkit-column-rule: 1px dashed black;
}
.controls {
    background:#C5DFF0;
    margin:20px auto;
    padding:20px;
    position:relative;
    width:800px;
    box-shadow:1px 1px 5px #111111;
    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;
}
.controls input[type=button] {
    border: 1px solid #000;
    background-color: #666;
    box-shadow: 0 1px 0 rgba(150, 150, 150, 0.5);
    color: #FFF;
    cursor: pointer;
    font-size: 14px;
    font-weight: bold;
    margin-right: 10px;
    padding: 8px 12px;
}
.controls input[type=button]:hover {
    background-color:#444;
}
.controls input[type=button]:active {
    background-color:#000;
}

 

Шаг 3. JavaScript

Автор добавил немного JS, чтобы мы могли поиграть со стилями (column-count и column-gap) в режиме реального времени.

$(function(){
    var iColumns = 3;
    var iGap = 3;
    var cont = document.getElementById('container');
    $('#less_cols').click(function(e) { // mouse click handler
        iColumns--; // decreasing amount of columns
        if (iColumns < 1) iColumns = 1; cont.style.MozColumnCount = iColumns; // apply styles cont.style.WebkitColumnCount = iColumns; }); $('#more_cols').click(function(e) { iColumns++; // increasing amount of columns if (iColumns > 5) iColumns = 5;
        cont.style.MozColumnCount = iColumns; // apply styles
        cont.style.WebkitColumnCount = iColumns;
    });
    $('#less_gap').click(function(e) {
        iGap--; // decreasing value of gap
        if (iGap < 0) iGap = 0; cont.style.MozColumnGap = iGap+'em'; // apply styles cont.style.WebkitColumnGap = iGap+'em'; }); $('#more_gap').click(function(e) { iGap++; // increasing value of gap if (iGap > 5) iGap = 5;
        cont.style.MozColumnGap = iGap+'em'; // apply styles
        cont.style.WebkitColumnGap = iGap+'em';
    });
});

Смотрите демо
Надеемся, этот урок вам пригодился. Скачать исходники урока вы можете на сайте автора

Автор — script-tutorials

Перевод — Дежурка

Возможно, вас также заинтересуют следующие статьи:


  • Опубликовано в css, июля 11, 2012
  • Метки: ,


Комментарии

  1. Петр
    Thumb up Thumb down 0

    Неработает в Опере и IE. А так идея хороша.

    kiber Ответ:

    Thumb up Thumb down +1

    в топку эти браузеры.

[an error occurred while processing the directive]


[an error occurred while processing the directive]