вторник, 26 ноября 2013 г.

Создание дерева графов на CSS 3



Файл index.html

<div class="tree">
<ul>
<li>
<a href="#">Parent</a>
<ul>
<li>
<a href="#">Child</a>
<ul>
<li>
<a href="#">Grand Child</a>
</li>
</ul>
</li>
<li>
<a href="#">Child</a>
<ul>
<li><a href="#">Grand Child</a></li>
<li>
<a href="#">Grand Child</a>
<ul>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
</ul>
</li>
<li><a href="#">Grand Child</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>

Файл index.css

* {margin: 0; padding: 0;}

.tree ul {
padding-top: 20px; position: relative;

transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}

.tree li {
float: left; text-align: center;
list-style-type: none;
position: relative;
padding: 20px 5px 0 5px;

transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}

/*We will use ::before and ::after to draw the connectors*/

.tree li::before, .tree li::after{
content: '';
position: absolute; top: 0; right: 50%;
border-top: 1px solid #ccc;
width: 50%; height: 20px;
}

.tree li::after{
right: auto; left: 50%;
border-left: 1px solid #ccc;
}

/*We need to remove left-right connectors from elements without
any siblings*/
.tree li:only-child::after, .tree li:only-child::before {
display: none;
}

/*Remove space from the top of single children*/
.tree li:only-child{ padding-top: 0;}

/*Remove left connector from first child and
right connector from last child*/
.tree li:first-child::before, .tree li:last-child::after{
border: 0 none;
}

/*Adding back the vertical connector to the last nodes*/
.tree li:last-child::before{
border-right: 1px solid #ccc;
border-radius: 0 5px 0 0;
-webkit-border-radius: 0 5px 0 0;
-moz-border-radius: 0 5px 0 0;
}

.tree li:first-child::after{
border-radius: 5px 0 0 0;
-webkit-border-radius: 5px 0 0 0;
-moz-border-radius: 5px 0 0 0;
}

/*Time to add downward connectors from parents*/
.tree ul ul::before{
content: '';
position: absolute; top: 0; left: 50%;
border-left: 1px solid #ccc;
width: 0; height: 20px;
}

.tree li a{
border: 1px solid #ccc;
padding: 5px 10px;
text-decoration: none;
color: #666;
font-family: arial, verdana, tahoma;
font-size: 11px;
display: inline-block;

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

transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}

/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}

/*Connector styles on hover*/
.tree li a:hover+ul li::after,
.tree li a:hover+ul li::before,
.tree li a:hover+ul::before,
.tree li a:hover+ul ul::before{
border-color:  #94a0b4;
}

четверг, 7 ноября 2013 г.

RECESS порядок записи CSS-правил

position
top
right
bottom
left
z-index
display
float
width
height
max-width
max-height
min-width
min-height
padding
padding-top
padding-right
padding-bottom
padding-left
margin
margin-top
margin-right
margin-bottom
margin-left
margin-collapse
margin-top-collapse
margin-right-collapse
margin-bottom-collapse
margin-left-collapse
overflow
overflow-x
overflow-y
clip
clear
font
font-family
font-size
font-smoothing
osx-font-smoothing
font-style
font-weight
hyphens
src
line-height
letter-spacing
word-spacing
color
text-align
text-decoration
text-indent
text-overflow
text-rendering
text-size-adjust
text-shadow
text-transform
word-break
word-wrap
white-space
vertical-align
list-style
list-style-type
list-style-position
list-style-image
pointer-events
cursor
background
background-attachment
background-color
background-image
background-position
background-repeat
background-size
border
border-collapse
border-top
border-right
border-bottom
border-left
border-color
border-image
border-top-color
border-right-color
border-bottom-color
border-left-color
border-spacing
border-style
border-top-style
border-right-style
border-bottom-style
border-left-style
border-width
border-top-width
border-right-width
border-bottom-width
border-left-width
border-radius
border-top-right-radius
border-bottom-right-radius
border-bottom-left-radius
border-top-left-radius
border-radius-topright
border-radius-bottomright
border-radius-bottomleft
border-radius-topleft
content
quotes
outline
outline-offset
opacity
filter
visibility
size
zoom
transform
box-align
box-flex
box-orient
box-pack
box-shadow
box-sizing
table-layout
animation
animation-delay
animation-duration
animation-iteration-count
animation-name
animation-play-state
animation-timing-function
animation-fill-mode
transition
transition-delay
transition-duration
transition-property
transition-timing-function
background-clip
backface-visibility
resize
appearance
user-select
interpolation-mode
direction
marks
page
set-link-source
unicode-bidi
speak

понедельник, 28 октября 2013 г.

БЭМ методология

.blockName-elementName--modificatorName
.blockName_elementName__modificatorName

.block-name__element-name__modificator-name

.digit-Progress             /* package-MainComponent */
.digit-Progress-bar       /* package-MainComponent-childElement */
.digit-Progress--small   /* package-MainComponent--variation */

Префикс package- (digit-) используется для создания пространства имён для того, чтобы не было конфликтов с названиями других packages/libraries/frameworks.

Использование тире (-) вместо подчёркивания (_) позволяет выделять отдельные части класс простым двойным кликом в реадкторе.

Для названий, состоящих из нескольких слов удобне использовать стиль camelCase.

Для выделения главного компонена его имя начинается с заглавной буквы в стиле CamelCase: .package-Component-childElement

Для визуального выделения вариаций мы используем двойное тире (--): .digit-Progress--small.

Для оформления заголовком можно использовать следующие примеры

/**
 * Class > Subclass > Variation
 */

/***************************************\
 * Class > Subclass > Variation
\***************************************/

пятница, 11 октября 2013 г.

CSS оформление Input File

HTML

<div class="file_upload">
    <button type="button">Выбрать</button>
    <div>Файл не выбран</div>
    <input type="file">
</div>

CSS

.file_upload{
    position: relative;
    overflow: hidden;
    font-size: 1em;        /* example */
    height: 2em;           /* example */
    line-height: 2em       /* the same as height */
}

.file_upload > button, .file_upload > div{
    cursor: pointer
}

.file_upload > button{
    float: right;
    width: 8em;            /* example */
    height: 100%
}

.file_upload > div{
    padding-left: 1em      /* example */
}

@media only screen and ( max-width: 500px ){  /* example */
    .file_upload > div{
        display: none
    }
    .file_upload > button{
        width: 100%
    }
}

.file_upload input[type=file]{
    position: absolute;
    top: 0;
    visibility: hidden
}

/* Making it beautiful */

.file_upload{
    border: 1px solid #ccc;
    border-radius: 3px;
    box-shadow: 0 0 5px rgba(0,0,0,0.1);
    transition: box-shadow 0.1s linear
}

.file_upload.focus{
    box-shadow: 0 0 5px rgba(0,30,255,0.4)
}

.file_upload > button{
    background: #7300df;
    transition: background 0.2s;
    border: 1px solid rgba(0,0,0,0.1);
    border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
    border-radius: 2px;
    box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05);
    color: #fff;
    text-shadow: #6200bd 0 -1px 0;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis
}

.file_upload:hover > button{
    background: #6200bd;
    text-shadow: #5d00b3 0 -1px 0
}

.file_upload:active > button{
    background: #5d00b3;
    box-shadow: 0 0 3px rgba(0,0,0,0.3) inset
}

JavaScript

$(function(){
    var wrapper = $( ".file_upload" ),
        inp = wrapper.find( "input" ),
        btn = wrapper.find( "button" ),
        lbl = wrapper.find( "div" );

    // Crutches for the :focus style:
    btn.focus(function(){
        wrapper.addClass( "focus" );
    }).blur(function(){
        wrapper.removeClass( "focus" );
    });

    // Yep, it works!
    btn.add( lbl ).click(function(){
        inp.click();
    });

    var file_api = ( window.File && window.FileReader && window.FileList && window.Blob ) ? true : false;

    inp.change(function(){

        var file_name;
        if( file_api && inp[ 0 ].files[ 0 ] )
            file_name = inp[ 0 ].files[ 0 ].name;
        else
            file_name = inp.val().replace( "C:\\fakepath\\", '' );
        if( ! file_name.length )
            return;

        if( lbl.is( ":visible" ) ){
            lbl.text( file_name );
            btn.text( "Выбрать" );
        }else
            btn.text( file_name );
    }).change();

});

$( window ).resize(function(){
    $( ".file_upload input" ).triggerHandler( "change" );
});

Полученное стилизованное поле выбора файла было успешно протестировано для всех трех способов в следующих браузерах:

FireFox 22.0 (Linux, Windows)
Opera 12.16 (Linux, Windows)
Internet Explorer 9
Chromium 27.0 (Linux)
Apple Safari (iOS 6.3.1)
Android browser (Android 2.3.6)
Android FireFox


Из плюсов всех рассмотренных в статье подходов можно выделить следующие основные:

Не используется Flash.
Элемент можно легко стилизовать средствами CSS, используя современные технологии адаптивного дизайна.
Поле можно заполнять и с клавиатуры.


Из основных минусов:

Необходимость использования JavaScript (касается всех способов).
Использование хаков CSS для «маскировочного» способа.
Необходимость писать дополнительные костыли для поля с атрибутом multiple (касается всех способов).
Некроссбраузерность — у всех способов отсутствует поддержка IE 8, а также необходимо использовать «браузерные» свойства CSS для поддержки остальных «старичков».
Решение на JavaScript не поддерживается всеми версиями Internet Explorer, а также некоторыми старыми версиями других популярных браузеров (хотя ими уже практически никто и не пользуется).

понедельник, 23 сентября 2013 г.

Абсолютное вертикальное и горизонтальное позиционирование блока

Просто блок

.Absolute-Center {
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

Блок внутри другого блока

.Center-Container {
  position: relative;
}

.Absolute-Center {
  width: 50%;
  height: 50%;
  overflow: auto;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

Внутри Viewport

.Absolute-Center.is-Fixed {
  position: fixed;
  z-index: 999;
}

Блок со смещением в сторону

.Absolute-Center.is-Right {
  left: auto; right: 20px;
  text-align: right;
}

.Absolute-Center.is-Left {
  right: auto; left: 20px;
  text-align: left;
}

Блок с изменяемыми размерами

.Absolute-Center.is-Responsive {
  width: 60%;
  height: 60%;
  min-width: 200px;
  max-width: 400px;
  padding: 40px;
}

Overflow - Блок с прокруткой содержимого внутри себя

.Absolute-Center.is-Overflow {
  overflow: auto;
}

Resizing

.Absolute-Center.is-Resizable {
  min-width: 20%;
  max-width: 80%;
  min-height: 20%;
  max-height: 80%;
  resize: both;
  overflow: auto;
}

Центрирование картинки

HTML

<img src="http://placekitten.com/g/500/200" class="Absolute-Center is-Image" alt="" />

CSS

.Absolute-Center.is-Image {
  height: auto;
}

.Absolute-Center.is-Image img {
  width: 100%;
  height: auto;
}

Переменная высота

JavaScript

/* Modernizr Test for Variable Height Content */
Modernizr.testStyles('#modernizr { display: table; height: 50px; width: 50px; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }', function(elem, rule) {
  Modernizr.addTest('absolutecentercontent', Math.round(window.innerHeight / 2 - 25) === elem.offsetTop);
});

CSS

.absolutecentercontent .Absolute-Center.is-Variable {
  display: table;
  height: auto;
}

Отрицательные Margin

.is-Negative {
        width: 300px;
        height: 200px;
        padding: 20px;
        position: absolute;
        top: 50%; left: 50%;
        margin-left: -170px; /* (width + padding)/2 */
        margin-top: -120px; /* (height + padding)/2 */
}

Трансформации

.is-Transformed {
  width: 50%;
  margin: auto;
  position: absolute;
  top: 50%; left: 50%;
  -webkit-transform: translate(-50%,-50%);
      - ms-transform: translate(-50%,-50%);
             transform: translate(-50%,-50%);
}

Табличная ячейка

HTML

<div class="Center-Container is-Table">
  <div class="Table-Cell">
    <div class="Center-Block">
    <!-- CONTENT -->
    </div>
  </div>
</div>

CSS

.Center-Container.is-Table { display: table; }
.is-Table .Table-Cell {
  display: table-cell;
  vertical-align: middle;
}
.is-Table .Center-Block {
  width: 50%;
  margin: 0 auto;
}

Инлайн-блок

HTML

<div class="Center-Container is-Inline">
  <div class="Center-Block">
    <!-- CONTENT -->
  </div>
</div>

CSS

.Center-Container.is-Inline {
  text-align: center;
  overflow: auto;
}

.Center-Container.is-Inline:after,
.is-Inline .Center-Block {
  display: inline-block;
  vertical-align: middle;
}

.Center-Container.is-Inline:after {
  content: '';
  height: 100%;
  margin-left: -0.25em; /* To offset spacing. May vary by font */
}

.is-Inline .Center-Block {
  max-width: 99%; /* Prevents issues with long content causes the content block to be pushed to the top */
  /* max-width: calc(100% - 0.25em) /* Only for IE9+ */
}

Flexbox

.Center-Container.is-Flexbox {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-align: center;
     -moz-box-align: center;
     -ms-flex-align: center;
  -webkit-align-items: center;
          align-items: center;
  -webkit-box-pack: center;
     -moz-box-pack: center;
     -ms-flex-pack: center;
  -webkit-justify-content: center;
          justify-content: center;
}

четверг, 19 сентября 2013 г.

Фиксированный заголовок и первая колонка таблицы

Файл index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Fix Header and First column Table</title>
<link href="index.css" rel="stylesheet" type="text/css">
<script src="jquery.js" type="text/javascript"></script>
<script src="index.js" type="text/javascript"></script>
</head>
<body>

<!-- Просто блок, в котором находится наша таблица -->

<div id="table-block">

    <!-- Весь заголовок таблицы -->

    <div class="table-header">

        <!-- Левый верхний блок DIV -->

            <div class="table-head-first">Компании</div>

        <!-- Правый верхний блок DIV -->

            <div class="table-head">
                <div class="table-head-wrapper">
                    <table>
                        <tr>
                            <td><div>Запасы</div></td>
                            <td><div>Основные средства</div></td>
                            <td><div>Долгоср. актив</div></td>
                            <td><div>Краткоср. активы</div></td>
                            <td><div>Актив</div></td>
                            <td><div>Период/тип отч.</div></td>
                        </tr>
                    </table>
                </div>
            </div>
       
    </div>
   
    <!-- Содержимое таблицы -->

        <!-- Левый нижний блок DIV -->

            <div class="table-data-first">
                <table>
                    <tr>
                        <td><div>VimpelCom Ltd. (ВымпелКом)</div></td>
                    </tr>
                    <tr>
                        <td><div>Газпром</div></td>
                    </tr>
                    <tr>
                        <td><div>Газпром Нефть</div></td>
                    </tr>
                    <tr>
                        <td><div>ЛУКОЙЛ НК</div></td>
                    </tr>
                    <tr>
                        <td><div> МТС</div></td>
                    </tr>
                    <tr>
                        <td><div>НЛМК</div></td>
                    </tr>
                    <tr>
                        <td><div>НОВАТЭК</div></td>
                    </tr>
                    <tr>
                        <td><div>Норильский никель ГМК</div></td>
                    </tr>
                    <tr>
                        <td><div>Роснефть НК</div></td>
                    </tr>
                    <tr>
                        <td><div>Сургутнефтегаз</div></td>
                    </tr>
                    <tr class="last">
                        <td><div></div></td>
                    </tr>
                </table>
            </div>
           
        <!-- Правый нижний блок DIV -->

            <div class="table-data">
                <div class="table-data-wrapper">
                    <table>      
                        <tr>
                            <td>167.00</td>
                            <td>15 666.00</td>
                            <td>45 820.00</td>
                            <td>9 540.00</td>
                            <td>55 360.00</td>
                            <td>2012 г. 4 кв., GAAP</td>
                        </tr>
                        <tr>
                            <td>14 779.36</td>
                            <td>251 452.22</td>
                            <td>310 661.81</td>
                            <td>77 469.19</td>
                            <td>388 131.00</td>
                            <td>2012 г. 4 кв., IAS</td>
                        </tr>
                        <tr>
                            <td>2 907.09</td>
                            <td>26 235.75</td>
                            <td>32 885.84</td>
                            <td>13 052.08</td>
                            <td>45 937.91</td>
                            <td>2013 г. 2 кв., IAS</td>
                        </tr>
                        <tr>
                            <td>7 848.00</td>
                            <td>69 640.00</td>
                            <td>77 799.00</td>
                            <td>23 375.00</td>
                            <td>101 174.00</td>
                            <td>2013 г. 1 кв., GAAP</td>
                        </tr>
                        <tr>
                            <td>264.87</td>
                            <td>8 762.52</td>
                            <td>1 171.89</td>
                            <td>3 607.77</td>
                            <td>15 324.00</td>
                            <td>2013 г. 1 кв., GAAP</td>
                        </tr>
                        <tr>
                            <td>2 530.19</td>
                            <td>10 981.40</td>
                            <td>12 100.62</td>
                            <td>5 537.20</td>
                            <td>17 637.82</td>
                            <td>2013 г. 2 кв., GAAP</td>
                        </tr>
                        <tr>
                            <td>99.41</td>
                            <td>6 347.93</td>
                            <td>13 021.92</td>
                            <td>1 873.19</td>
                            <td>14 895.11</td>
                            <td>2012 г. 4 кв., IAS</td>
                        </tr>
                        <tr>
                            <td>3 195.00</td>
                            <td>11 502.00</td>
                            <td></td>
                            <td>7 262.00</td>
                            <td>20 226.00</td>
                            <td>2013 г. 2 кв., IAS</td>
                        </tr>
                        <tr>
                            <td>5 990.54</td>
                            <td>150 536.59</td>
                            <td>76 978.72</td>
                            <td>42 094.85</td>
                            <td>219 073.57</td>
                            <td>2013 г. 2 кв., IAS</td>
                        </tr>
                        <tr>
                            <td>1 689.58</td>
                            <td>29 604.01</td>
                            <td>48 949.39</td>
                            <td>17 656.16</td>
                            <td>66 605.54</td>
                            <td>2012 г. 4 кв., IAS</td>
                        </tr>
                        <tr class="last">
                            <td><div></div></td>
                            <td><div></div></td>
                            <td><div></div></td>
                            <td><div></div></td>
                            <td><div></div></td>
                            <td><div></div></td>
                        </tr>
                    </table>
                </div>
            </div>

</div>

</body>
</html>

Файл index.css

/*\
 * ===============================================>
 * Reset CSS
 * ===============================================>
\*/

html {
font-size: 100.01%;  /* Bug fix for Opera */
}

body {
width: 1000px;
position: relative; /* Bug fix for IE 6 */
margin: 0;
padding: 0;
margin-left: auto;
margin-right: auto;
text-align: center;
font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif;
font-size: 62.5%;
background-color: #bbbbbb;
color: #333333;
}

div,h1,h2,h3,h4,h5,h6,p,img,ol,ul,li,table,th,td,form,select,fieldset {
margin: 0;
padding: 0;
text-align: left;
}

article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
    display: block;
}

ol,ul {
list-style: none;
}

table {
border: 0px; /* border="0" */
border-collapse: collapse; /* cellspacing="0" */
}

table tr th {
padding: 0px; /* cellpadding="0" */
}

table tr td {
padding: 0px; /* cellpadding="0" */
}

input,textarea,select {
font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif;
}

textarea {
resize: none;
}

a img {
border: none;
}

a {
color: #333333;
text-decoration: underline;
}

a:hover {
color: #000000;
}

a:active {
text-decoration: none;
}

/* Firefox anchor border remove */
a:active,a:focus,img {
outline: 0;
}

/*\
 * ===============================================>
 * Fix Header and First column Table style
 * ===============================================>
\*/

/* Просто блок, в котором находится наша таблица */

div#table-block {
    width: 900px;
    height: 400px;
    padding: 5px;
    background-color: #ffffff;
    border: 1px solid #000000;
    font-size: 1.3em;
    line-height: 22px;
    overflow: hidden;
}

/* Общие стили для всей таблицы*/

div#table-block table {
    width: auto;
/*    border-collapse: separate !important; */
}

div#table-block table tr td {
    white-space: nowrap;
}

div#table-block table tr td div {
    overflow: hidden;
}

div.table-header {
    border: 1px solid #999999; /* Установлены все границы для заголовка таблицы */
}

div.table-head-wrapper,
div.table-data-wrapper {
    width: 100000px;
}

/* Левый верхний блок DIV */

div.table-head-first {
    float: left;
    *display: inline;
    _display: inline;
    overflow: hidden;
    width: 260px;
    _margin-right: -3px;
    height: 32px;
    _height: 28px;
    line-height: 16px;
    padding: 0 5px;
    _padding-bottom: 4px;
    border-right: 1px solid #999999;
    text-align: center;
}

/* Правый верхний блок DIV */

div.table-head {
    line-height: 16px;
    overflow: hidden;
}

div.table-head table tr td {
    padding: 0 15px;
    border-right: 1px solid #999999;
    vertical-align: top;
    text-align: center;
}

div.table-head table tr td div {
    height: 32px;
    text-align: center;
}

/* Левый нижний блок DIV */

div.table-data-first {height: 197px; /* Значение для примера */
    float: left;
    *display: inline;
    _display: inline;
    overflow: hidden;
    _margin-right: -3px;
    border-left: 1px solid #999999;
    border-bottom: 1px solid #999999;
}

div.table-data-first table tr td {
    padding: 0 5px;
    _padding: 1px 5px;
    border-bottom: 1px solid #999999;
}

div.table-data-first table tr td div {
    width: 260px;
}

div.table-data-first table tr.last td  {
    border-bottom: none;
}

/* Правый нижний блок DIV */

div.table-data {height: 215px; /* Значение для примера */
    overflow: scroll;
    border-left: 1px solid #999999;
    border-right: 1px solid #999999;
    border-bottom: 1px solid #999999;
}

div.table-data table tr td {
    padding: 0 15px;
    _padding: 1px 15px;
    border-right: 1px solid #999999;
    border-bottom: 1px solid #999999;
    text-align: right;
}

div.table-data table tr.last td  {
    border-bottom: none;
}


Файл index.js

// НАЧАЛО - МИНИМАЛЬНО НЕОБХОДИМЫЙ КОД ДЛЯ ВЫРАВНИВАНИЯ И ПРОКРУЧИВАНИЯ ТАБЛИЦЫ

// Возвращает ширину скролбара
function getScrollbarWidth() {
    var scrollbarWidth
        , blockWidthWithoutScrollbar
        , blockWidthWithScrollbar
        , div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div></div>');
   
    $('body').append(div);

    blockWidthWithoutScrollbar = $('div', div).innerWidth();

    div.css('overflow-y', 'scroll');

    blockWidthWithScrollbar = $('div', div).innerWidth();

    $(div).remove();
    scrollbarWidth = blockWidthWithoutScrollbar - blockWidthWithScrollbar;

    if (!scrollbarWidth) {
        scrollbarWidth = 16;
    }

    return scrollbarWidth;
}

// Возвращает ширину 1em в пикселях
function getEmWidth(element) {
    var tmp = $('<div style="position: absolute; z-index: -1000; width: 1em; margin: 0; padding: 0;"></div>')
        , width;
       
    element.append(tmp);
    width = tmp.width();
    $(tmp).remove();
   
    return width;
}

// Выравнивает ширину ячеек таблицы
function alignTableCellsWidth(table) {
    var headTdCells = table.find('.table-head td div')
        , em = getEmWidth(table.find('.table-data td:last'))
        , leftPlusRightBorderWidth = 2;
               
    table.find('.table-data table tr.last, .table-side table tr.last').remove();
    table.find('.table-data table').append('<tr class="last"></tr>');
    table.find('.table-side table').append('<tr class="last"><td><div></div></td></tr>');

    headTdCells.each(function(index){
        var td = $('<td><div></div></td>');
        table.find('.table-data tr.last').append(td);

        var dataTdCell = td.find('div');
        var thWidth = $(this).width();
        var tdWidth = dataTdCell.width();
        var emWidth;

        if (thWidth > tdWidth){
            emWidth = Math.floor(thWidth / em) + 2;
        } else {
            emWidth = Math.floor(tdWidth / em) + 2;
        }
        dataTdCell.css('width', emWidth + 'em');
        $(this).css('width', emWidth + 'em');
    });

    table.find('.table-head-wrapper').width(table.find('.table-head-wrapper table').width() + getScrollbarWidth() + leftPlusRightBorderWidth);
    table.find('.table-data-wrapper').width(table.find('.table-data-wrapper table').width());
}

// Прокрутка для таблицы
function initTableScroll () {
    $('.table-data:first').scroll(function(){
        var top = $(this).scrollTop();
        var left = $(this).scrollLeft();

        $('.table-data-first').scrollTop(top);
        $('.table-head').scrollLeft(left);
    });
}

// КОНЕЦ - МИНИМАЛЬНО НЕОБХОДИМЫЙ КОД ДЛЯ ВЫРАВНИВАНИЯ И ПРОКРУЧИВАНИЯ ТАБЛИЦЫ

// НАЧАЛО - ДОПОЛНИТЕЛЬНЫЙ КОД

//Сбрасывает стили таблицы
function resetTable(table){
    table.find('.table-head-wrapper, .table-data-wrapper, .table-head td div, .table-data td div').removeAttr('style');
}

// КОНЕЦ- ДОПОЛНИТЕЛЬНЫЙ КОД

$(document).ready(function(){
// НАЧАЛО - МИНИМАЛЬНО НЕОБХОДИМЫЙ КОД ДЛЯ ВЫРАВНИВАНИЯ И ПРОКРУЧИВАНИЯ ТАБЛИЦЫ
    alignTableCellsWidth($('#table-block'));
    initTableScroll();
// КОНЕЦ - МИНИМАЛЬНО НЕОБХОДИМЫЙ КОД ДЛЯ ВЫРАВНИВАНИЯ И ПРОКРУЧИВАНИЯ ТАБЛИЦЫ
});

Фиксированный заголовок таблицы

Самый простой и лучший способ зафиксировать заголовок таблицы.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>

table {
    border: 0px; /* border="0" */
    border-collapse: collapse; /* cellspacing="0" */
}

table tr th {
    padding: 0px; /* cellpadding="0" */
}

table tr td {
    padding: 0px; /* cellpadding="0" */
}

div.header-wrapper {
    width: 320px;
    border: 1px solid black;
    border-bottom: none;
}

div.body-wrapper {
    overflow: auto;
    width: 320px;
    height: 110px;
    border: 1px solid black;
    border-top: none;
}

table.header {
    width: 300px;
    border-bottom: 1px solid black;
}

table.body {
    width: 300px;
}

table.header tr td {
    border-right: 1px solid black;
}

table.body tr td {
    border-right: 1px solid black;
    border-bottom: 1px solid black;
}

table.body tr.last-row td {
    border-bottom: none;
}

table tr td.first {
    width: 150px;
}

</style>
<title>Fix Table Header</title>
</head>
<body>

<div class="header-wrapper">
    <table class="header">
        <tr>
            <td class="first">Column 1</td>
            <td class="last">Column 2</td>
        </tr>
    </table>
</div>

<div class="body-wrapper">
    <table class="body" >
    <tr>
        <td class="first">Value 1</td>
        <td class="last">Value 2</td>
    </tr>
    <tr>
        <td class="first">Value 1</td>
        <td class="last">Value 2</td>
    </tr>
    <tr>
        <td class="first">Value 1</td>
        <td class="last">Value 2</td>
    </tr>
    <tr>
        <td class="first">Value 1</td>
        <td class="last">Value 2</td>
    </tr>
    <tr>
        <td class="first">Value 1</td>
        <td class="last">Value 2</td>
    </tr>
    <tr class="last-row">
        <td class="first">Value 1</td>
        <td class="last">Value 2</td>
    </tr>
    </table>
</div>

</body>
</html>