Bootstrap Grid System
Bootstrap’s grid system allows up to 12 columns across the page.
If you do not want to use all 12 column individually, you can group the columns together to create wider columns:
span 1 | span 1 | span 1 | span 1 | span 1 | span 1 | span 1 | span 1 | span 1 | span 1 | span 1 | span 1 |
span 4 | span 4 | span 4 | |||||||||
span 4 | span 8 | ||||||||||
span 6 | span 6 | ||||||||||
span 12 |
Bootstrap’s grid system is responsive, and the columns will re-arrange depending on the screen size: On a big screen it might look better with the content organized in three columns, but on a small screen it would be better if the content items were stacked on top of each other.
Tip: Remember that grid columns should add up to twelve for a row. More than that, columns will stack no matter the viewport.
Grid Classes
The Bootstrap grid system has four classes:
- xs (for phones — screens less than 768px wide)
- sm (for tablets — screens equal to or greater than 768px wide)
- md (for small laptops — screens equal to or greater than 992px wide)
- lg (for laptops and desktops — screens equal to or greater than 1200px wide)
The classes above can be combined to create more dynamic and flexible layouts.
Tip: Each class scales up, so if you wish to set the same widths for xs and sm, you only need to specify xs.
Grid System Rules
Some Bootstrap grid system rules:
- Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding
- Use rows to create horizontal groups of columns
- Content should be placed within columns, and only columns may be immediate children of rows
- Predefined classes like .row and .col-sm-4 are available for quickly making grid layouts
- Columns create gutters (gaps between column content) via padding. That padding is offset in rows for the first and last column via negative margin on .rows
- Grid columns are created by specifying the number of 12 available columns you wish to span. For example, three equal columns would use three .col-sm-4
- Column widths are in percentage, so they are always fluid and sized relative to their parent element
Basic Structure of a Bootstrap Grid
The following is a basic structure of a Bootstrap grid:
So, to create the layout you want, create a container ( ). Next, create a row ( ). Then, add the desired number of columns (tags with appropriate .col-*-* classes). Note that numbers in .col-*-* should always add up to 12 for each row.
So for the first row in our example above, the markup defines a with class .col-sm-12 , which is going to take up twelve columns of space (100% of the width).
The next row specifies three columns; Bootstrap lines these up next to each other, where .col-sm-4 takes about 33.3% of the width (33.3% + 33.3% + 33.3%).
In our third row, we have added one extra class to each column ( .col-lg-9 and .col-lg-3 ). This means that when the page is viewed on a larger screen it should split the column width to 75% ( .col-lg-9 ) and 25% ( .col-lg-3 ). As we also have specified the small classes, the columns will split to 66% ( .col-sm-8 ) and 33% ( .col-sm-4 ) for small AND medium screens (scales up). This is useful for re-arranging the layout for different screen sizes.
Grid Options
The following table summarizes how the Bootstrap grid system works across multiple devices:
Extra small | Small >=768px | Medium >=992px | Large >=1200px | |
---|---|---|---|---|
Class prefix | .col-xs- | .col-sm- | .col-md- | .col-lg- |
Suitable for | Phones | Tablets | Small Laptops | Laptops & Desktops |
Grid behaviour | Horizontal at all times | Collapsed to start, horizontal above breakpoints | Collapsed to start, horizontal above breakpoints | Collapsed to start, horizontal above breakpoints |
Container width | None (auto) | 750px | 970px | 1170px |
# of columns | 12 | 12 | 12 | 12 |
Column width | Auto | ~62px | ~81px | ~97px |
Gutter width | 30px (15px on each side of a column) | 30px (15px on each side of a column) | 30px (15px on each side of a column) | 30px (15px on each side of a column) |
Nestable | Yes | Yes | Yes | Yes |
Offsets | Yes | Yes | Yes | Yes |
Column ordering | Yes | Yes | Yes | Yes |
Examples
The next chapters shows examples of grid systems for different devices:
Did You Know?
W3.CSS is an excellent alternative to Bootstrap.
W3.CSS is smaller, faster, and easier to use.
If you want to learn W3.CSS, go to our W3.CSS Tutorial.
Система сеток
Используйте нашу мощную сетку flexbox, ориентированную на мобильные устройства, для создания макетов всех форм и размеров благодаря системе из двенадцати колонок, шести адаптивным уровням по умолчанию, переменным и миксинам Sass, а также десяткам предопределенных классов.
Пример
Система сеток Bootstrap использует серию контейнеров, строк и колонок для компоновки и выравнивания содержимого. Он построен с помощью flexbox и полностью адаптивен. Ниже приведен пример и подробное объяснение того, как объединяется сетка.
Новичок или незнаком с flexbox? Прочтите это руководство по flexbox на CSS Tricks для получения справочной информации, терминологии, рекомендаций и фрагментов кода.
div class="container"> div class="row"> div class="col"> Колонка div> div class="col"> Колонка div> div class="col"> Колонка div> div> div>
В приведенном выше примере создаются три колонки одинаковой ширины на всех устройствах и в окнах просмотра с использованием наших предопределенных классов сетки. Эти колонки центрируются на странице с родительским .container .
Как это устроено
Вот как объединяется сетка:
- Наша сетка поддерживает шесть адаптивных контрольных точек. Контрольные точки основаны на медиа-запросах min-width , то есть они влияют на эту контрольную точку и все вышеперечисленные (например, .col-sm-4 применяется к sm , md , lg , xl и xxl ). Это означает, что Вы можете управлять размером и поведением контейнера и колонки с помощью каждой контрольной точки.
- Контейнеры центрируют и размещают Ваш контент по горизонтали. Используйте .container для адаптивной ширины в пикселях, .container-fluid для width: 100% во всех окнах просмотра и на всех устройствах или адаптивный контейнер (например, .container-md ) для комбинации подвижной и пиксельной ширины.
- Ряды (rows) являются оболочками для колонок. Каждая колонка имеет горизонтальный padding (называемый промежутком) для управления пространством между ними. Затем этому padding противодействуют строки с отрицательными полями, чтобы обеспечить визуальное выравнивание содержимого колонок по левой стороне. Строки также поддерживают классы модификаторов для единообразного применения размеров колонок и классов промежутков для изменения интервала Вашего контента.
- Колонки невероятно гибкие. В каждой строке доступно 12 шаблонов колонок, что позволяет создавать различные комбинации элементов, охватывающих любое количество колонок. Классы колонок указывают количество колонок шаблона, которые необходимо охватить (например, col-4 охватывает четыре). width задаются в процентах, поэтому Вы всегда имеете одинаковый относительный размер.
- Промежутки также являются адаптивными и настраиваемыми.Доступны классы промежутков во всех контрольных точках с теми же размерами, что и наши поля и отступы. Измените горизонтальные промежутки на классы .gx-* , вертикальные промежутки на .gy-* , или все промежутки на классы .g-* . .g-0 также доступен для удаления промежутков.
- Переменные Sass, карты и миксины питают сетку. Если Вы не хотите использовать предопределенные классы сетки в Bootstrap, Вы можете использовать наш источник Sass сетки чтобы создать свой собственный с большим количеством семантическая разметка. Мы также включаем некоторые настраиваемые свойства CSS для использования этих переменных Sass для еще большей гибкости для Вас.
Параметры сетки
Система сеток Bootstrap может адаптироваться ко всем шести контрольным точкам по умолчанию и любым настраиваемым Вами контрольным точкам. Шесть уровней сетки по умолчанию следующие:
- Очень маленький — Extra small (xs)
- Маленький — Small (sm)
- Средний — Medium (md)
- Большой — Large (lg)
- Очень большой — Extra large (xl)
- Огромный — Extra extra large (xxl)
Как отмечалось выше, каждая из этих контрольных точек имеет собственный контейнер, уникальный префикс класса и модификаторы. Вот как меняется сетка в этих контрольных точках:
xs | sm ≥576px | md ≥768px | lg ≥992px | xl ≥1200px | xxl ≥1400px | |
---|---|---|---|---|---|---|
Контейнер max-width | Ничего (авто) | 540px | 720px | 960px | 1140px | 1320px |
Префикс класса | .col- | .col-sm- | .col-md- | .col-lg- | .col-xl- | .col-xxl- |
# колонок | 12 | |||||
Ширина промежутка | 1.5rem (.75rem слева и справа) | |||||
Индивидуальные промежутки | Да | |||||
Вкладываемые | Да | |||||
Порядок колонок | Да |
Колонки с автоматической компоновкой
Используйте классы колонок, специфичные для контрольной точки, для удобного определения размера колонки без явного нумерованного класса, например .col-sm-6 .
Равная ширина
Например, вот два макета сетки, которые применяются к каждому устройству и окну просмотра, от xs до xxl . Добавьте любое количество классов без единиц измерения для каждой нужной контрольной точки, и каждая колонка будет одинаковой ширины.
Grid system
Use our powerful mobile-first flexbox grid to build layouts of all shapes and sizes thanks to a twelve column system, five default responsive tiers, Sass variables and mixins, and dozens of predefined classes.
How it works
Bootstrap’s grid system uses a series of containers, rows, and columns to layout and align content. It’s built with flexbox and is fully responsive. Below is an example and an in-depth look at how the grid comes together.
New to or unfamiliar with flexbox? Read this CSS Tricks flexbox guide for background, terminology, guidelines, and code snippets.
class="container"> class="row"> class="col-sm"> One of three columns class="col-sm"> One of three columns class="col-sm"> One of three columns
The above example creates three equal-width columns on small, medium, large, and extra large devices using our predefined grid classes. Those columns are centered in the page with the parent .container .
Breaking it down, here’s how it works:
- Containers provide a means to center and horizontally pad your site’s contents. Use .container for a responsive pixel width or .container-fluid for width: 100% across all viewport and device sizes.
- Rows are wrappers for columns. Each column has horizontal padding (called a gutter) for controlling the space between them. This padding is then counteracted on the rows with negative margins. This way, all the content in your columns is visually aligned down the left side.
- In a grid layout, content must be placed within columns and only columns may be immediate children of rows.
- Thanks to flexbox, grid columns without a specified width will automatically layout as equal width columns. For example, four instances of .col-sm will each automatically be 25% wide from the small breakpoint and up. See the auto-layout columns section for more examples.
- Column classes indicate the number of columns you’d like to use out of the possible 12 per row. So, if you want three equal-width columns across, you can use .col-4 .
- Column width s are set in percentages, so they’re always fluid and sized relative to their parent element.
- Columns have horizontal padding to create the gutters between individual columns, however, you can remove the margin from rows and padding from columns with .no-gutters on the .row .
- To make the grid responsive, there are five grid breakpoints, one for each responsive breakpoint: all breakpoints (extra small), small, medium, large, and extra large.
- Grid breakpoints are based on minimum width media queries, meaning they apply to that one breakpoint and all those above it (e.g., .col-sm-4 applies to small, medium, large, and extra large devices, but not the first xs breakpoint).
- You can use predefined grid classes (like .col-4 ) or Sass mixins for more semantic markup.
Grid options
While Bootstrap uses em s or rem s for defining most sizes, px s are used for grid breakpoints and container widths. This is because the viewport width is in pixels and does not change with the font size.
See how aspects of the Bootstrap grid system work across multiple devices with a handy table.
Extra small | Small ≥576px | Medium ≥768px | Large ≥992px | Extra large ≥1200px | |
---|---|---|---|---|---|
Max container width | None (auto) | 540px | 720px | 960px | 1140px |
Class prefix | .col- | .col-sm- | .col-md- | .col-lg- | .col-xl- |
# of columns | 12 | ||||
Gutter width | 30px (15px on each side of a column) | ||||
Nestable | Yes | ||||
Column ordering | Yes |
Auto-layout columns
Utilize breakpoint-specific column classes for easy column sizing without an explicit numbered class like .col-sm-6 .
Equal-width
For example, here are two grid layouts that apply to every device and viewport, from xs to xl . Add any number of unit-less classes for each breakpoint you need and every column will be the same width.