Сниппеты Bootstrap
- Bootstrap 3:
col-md-offset-1 - Bootstrap 4:
offset-md-1
Пример: этот div будет выглядеть как столбец шириной 10 колонок с отступами в одну колонку слева и справа:
<div class="col-md-10 col-md-offset-1">Test</div>
Миксин в Sass:
@include media-breakpoint-up(md) {
@include make-col-offset(1);
}
Иногда бывает нужно сделать так, чтобы .container на размерах типа sm или md становился 100% ширины (на xs он и так 100%).
@include media-breakpoint-down(md) {
.container { width: 100%; max-width: none; }
}
Используем Flex:
- добавляем Flex любому
divс помощью классаd-flex; - или используем тот факт, что в Bootstrap 4 у
rowуже назначенFlex.
<div class="d-flex align-items-center" style="min-height: 100px;">
<p>Выровненный по вертикали текст</p>
</div>
<div class="container">
<div class="row align-items-center" style="min-height: 100px;">
<p>Выровненный по вертикали текст</p>
</div>
</div>
<div class="d-flex align-items-center justify-content-center" style="min-height: 100px;">
<p>Выровненный по вертикали и горизонтали текст</p>
</div>
<div class="container">
<div class="row align-items-center justify-content-center" style="min-height: 100px;">
<p>Выровненный по вертикали и горизонтали текст</p>
</div>
</div>
Готовый сниппет:
.centered {
@extend .d-flex;
@extend .align-items-center;
@extend .justify-content-center;
}
Или на чистом CSS:
.centered {
display: flex;
align-items: center;
justify-content: center;
}
Добавить class к тэгу img (пример):
- Bootstrap 3:
img-responsive - Bootstrap 4:
img-fluid
- Bootstrap 4:
@include gradient-y(dodgerblue, gold, 10%, 100%);
Здесь:
gradient-y— вертикальный градиент; для горизонтального используйтеgradient-xdodgerblue, gold— начальный и конечный цвет градиента;10%, 100%— сдвиг начала градиента в начале и в конце. В данном случае 10% означает, что сначала (сверху) 10% занимает чистый цвет, затем идет градиент, а 100% означает, что градиент идет до самого конца. Чтобы сдвинуть нижний край градиента на 10%, нужно второе значение сделать не 100%, а 90%.
К ссылке добавляем класс .stretched-link, к врапперу — position: relative;
Типичный пример — кнопка:
<ul class="tag__list">
<li class="tag__item">
<a class="tag__link" href="#">Анкор 1</a>
</li>
<li class="tag__item">
<a class="tag__link" href="#">Анкор 2</a>
</li>
</ul>
.tag__list {
list-style: none;
}
.tag__item {
position: relative; // Обязательно
display: inline-block;
padding: .5rem 1rem;
background-color: silver;
&:hover {
background-color: orange;
}
}
.tag__link {
@extend .stretched-link; // Обязательно
}
Кнопка с ссылкой внутри:
<button>
<a href="#">Отправить</a>
</button>
Стиль cta (от Call to Action) с разметкой по BEM:
<button class="cta__button">
<a class="cta__link" href="#">Отправить</a>
</button>
.cta__button {
@extend .btn; // необязательно — импортируем стандартные стили кнопок Bootstrap
position: relative; // обязательно для .stretched-link
background-color: pink;
&:hover { background-color: red; }
}
.cta__link {
@extend .stretched-link; // расширяем кликабельную область до всей кнопки
text-decoration: none;
&:hover { color: white; }
}
Выравнивание
<p class="text-justify">Justified text.</p>
<p class="text-xs-left">Left aligned text on all viewport sizes.</p>
<p class="text-xs-center">Center aligned text on all viewport sizes.</p>
<p class="text-xs-right">Right aligned text on all viewport sizes.</p>
Начертание
<p class="font-weight-bold">Bold text.</p>
<p class="font-weight-normal">Normal weight text.</p>
<p class="font-italic">Italic text.</p>
Отключение переноса слов
<p class="text-nowrap">No wrap text.</p>
.nav > li > a { white-space: nowrap; }
Регистр букв
<ul class="list-unstyled">
<li>Lorem ipsum dolor sit amet</li>
</ul>
Bootstrap 3:
<ul class="list-inline">
<li>Home</li>
<li>About Us</li>
<li>Products</li>
<li>Contact</li>
</ul>
Bootstrap 4 — комбинация двух стилей: .list-inline и .list-inline-item.
<ul class="list-inline">
<li class="list-inline-item">Текст</li>
<li class="list-inline-item">Текст</li>
</ul>
![]() |
<ul class="list-group">
<li class="list-group-item">Pictures</li>
<li class="list-group-item">Documents</li>
<li class="list-group-item">Music</li>
<li class="list-group-item">Videos</li>
</ul>
|
По умолчанию размеры полей меняются 3 стилями:
.form-control .form-control-sm .form-control-lg
Последние два используются только в паре с первым:
<input class="form-control form-control-lg">
Аналогично подписи:
.col-form-label .col-form-label-sm .col-form-label-lg
Если нужно сильнее изменить размер поля — например, еще больше увеличить — добавляем в _custom_variables.scss строку и увеличиваем параметры:
$input-height-lg: calc(1.5em + .5rem + 2px);
Приведены значения параметров по умолчанию. Они вычисляется здесь node_modules/bootstrap/scss/_variables.scss:
$input-height-lg: add($input-line-height-lg * 1em, add($input-padding-y-lg * 2, $input-height-border, false)) !default;
где:
$input-line-height-lg = $input-btn-line-height-lg = $line-height-lg: 1.5;
$input-padding-y-lg = $input-btn-padding-y-lg: .5rem;
$input-height-border = $input-border-width * 2;
$input-border-width = $input-btn-border-width = $border-width: 1px;
$input-padding-x-lg = $input-btn-padding-x-lg: 1rem;
Соответственно, можно менять не напрямую $input-height-lg, а какие-то из изначальных параметров.
$input-font-size-sm = $input-btn-font-size-sm = $font-size-sm = $font-size-base * .875;
$input-font-size-lg = $input-btn-font-size-lg = $font-size-lg = $font-size-base * 1.25;
$font-size-base: 1rem !default; // Assumes the browser default, typically `16px`
npm install @tkrotoff/bootstrap-floating-label
main-bootstrap.scss:
@import "bootstrap";
@import '../../../../node_modules/@tkrotoff/bootstrap-floating-label/src/bootstrap4-floating-label';
HTML:
<div class="container">
<form class="row mt-5 mb-5">
<div class="col-6">
<div class="form-group floating-label">
<input id="name1" class="form-control form-control-lg" placeholder=" " />
<label for="name1">Ваше имя</label>
</div>
<div class="form-group floating-label">
<input id="phone1" type="text" class="form-control form-control-lg" placeholder=" ">
<label for="phone1">Ваш номер телефона</label>
</div>
<button type="submit" class="btn btn-primary">Отправить</button>
</div>
</form>
</div>
- https://getbootstrap.com/docs/4.5/layout/overview/#responsive-breakpoints
- http://saddamazad.com/2015/12/bootstrap-4-media-queries-using-sass/
// Extra small devices (portrait phones, less than 576px)
// No media query for `xs` since this is the default in Bootstrap
// @include media-breakpoint-up(xs) {} // не нужен
// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { }
@include media-breakpoint-up(sm) {}
// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { }
@include media-breakpoint-up(md) {}
// Large devices (desktops, 992px and up)
@media (min-width: 992px) { }
@include media-breakpoint-up(lg) {}
// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { }
@include media-breakpoint-up(xl) {}
// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575.98px) { }
@include media-breakpoint-down(xs) {}
// Small devices (landscape phones, less than 768px)
@media (max-width: 767.98px) { }
@include media-breakpoint-down(sm) {}
// Medium devices (tablets, less than 992px)
@media (max-width: 991.98px) { }
@include media-breakpoint-down(md) {}
// Large devices (desktops, less than 1200px)
@media (max-width: 1199.98px) { }
@include media-breakpoint-down(lg) {}
// Extra large devices (large desktops)
// @include media-breakpoint-down(xl) {} // не нужен
/* No media query since the extra-large breakpoint has no upper bound on its width */
// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575.98px) { }
@include media-breakpoint-only(xs) {}
// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) and (max-width: 767.98px) { }
@include media-breakpoint-only(sm) {}
// Medium devices (tablets, 768px and up)
@media (min-width: 768px) and (max-width: 991.98px) { }
@include media-breakpoint-only(md) {}
// Large devices (desktops, 992px and up)
@media (min-width: 992px) and (max-width: 1199.98px) { }
@include media-breakpoint-only(lg) {}
// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { }
@include media-breakpoint-only(xl) {}
$screen-xs-max: 767px
$screen-sm-min: 768px;
$screen-md-min: 992px
$screen-lg-min: 1200px;
@media(max-width: $screen-xs-max) {} /* Extra Small: ≤ 767px */
@media(min-width: $screen-sm-min) {} /* Small: 768px-991px */
@media(min-width: $screen-md-min) {} /* Medium: 992px-1199px */
@media(min-width: $screen-lg-min) {} /* Large: > 1200px */
/* OR */
@media(max-width: 767px) { } /* Extra Small */
@media(min-width: 768px) and (max-width: 991px) { } /* Small */
@media(min-width: 992px) and (max-width: 1199px) { } /* Medium */
@media(min-width: 1200px) { } /* Large */
Old school CSS values
MOBILE FIRST QUERIES
@media only screen and (min-width : 320px) { } /* Custom, iPhone Retina */
@media only screen and (min-width : 480px) { } /* Extra Small Devices, Phones */
@media only screen and (min-width : 768px) { } /* Small Devices, Tablets */
@media only screen and (min-width : 992px) { } /* Medium Devices, Desktops */
@media only screen and (min-width : 1200px) { } /* Large Devices, Wide Screens */
DESKTOP FIRST QUERIES
Use this if you are designing a full-width layout first. This is not the recommended way with Bootstrap 3.
@media only screen and (max-width : 1200px) { } /* Large Devices, Wide Screens */
@media only screen and (max-width : 992px) { } /* Medium Devices, Desktops */
@media only screen and (max-width : 768px) { } /* Small Devices, Tablets */
@media only screen and (max-width : 480px) { } /* Extra Small Devices, Phones */
@media only screen and (max-width : 320px) { } /* Custom, iPhone Retina */
Note the difference between the two ways of defining media queries: mobile first use min-width and desktop first uses max-width.
Which means that the mobile first way will show your default CSS (the stuff outside of any media query) until a larger screen width is used and the desktop first will show your default until a smaller screen width is used.
bootstrap/scss/mixins/_grid.scss
https://getbootstrap.com/docs/4.1/layout/grid/#mixins
@include make-col-ready();
@include make-col(12);
В HTML должен находиться внутри container > row:
<div class="container">
<div class="row">
Удобно использовать, например, так:
div {
@include media-breakpoint-up(xs) { @include make-col(12); }
@include media-breakpoint-up(sm) { @include make-col(6); }
@include media-breakpoint-up(md) { @include make-col(5); }
@include media-breakpoint-up(lg) { @include make-col(3); }
}
Реальный пример:
// Основной шаблон внутренних страниц: основное поле 8 колонок с отступом слева 1 колонка и справа 3 колонки
.cols-1-8-3 {
@include make-col-ready();
@include make-col(12); // сначала на мобильных размерах ширина контейнера — 12 колонок
@include media-breakpoint-up(md) { // начиная с MD ширина контейнера — 9 колонок
@include make-col(9);
}
@include media-breakpoint-up(lg) { // начиная с LG добавляется отступ слева в 1 колонку, ширина контента — 8 колонок, справа остается 3 колонки
@include make-col-offset(1);
@include make-col(8);
}
}
<div class="container">
<div class="row">
<div class="cols-1-8-3">
<p>Текст</p>
</div>
</div>
</div>
@include transition(all .5s linear);
Используем миксин .img-retina
.img-retina("/img/bg-1x.png", "/img/bg-2x.png", 100px, 100px);
Последние два значения — ширина и высота.







