Chuyển tới nội dung
Home » Grid System In Bootstrap 4 | Grid System Rules

Grid System In Bootstrap 4 | Grid System Rules

Bootstrap 4 Tutorial #5 - Grid Basics

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.

Bootstrap 4 Tutorial #5 - Grid Basics
Bootstrap 4 Tutorial #5 – Grid Basics

Grid Classes

The Bootstrap 4 grid system has five classes:


  • .col-

    (extra small devices – screen width less than 576px)

  • .col-sm-

    (small devices – screen width equal to or greater than 576px)

  • .col-md-

    (medium devices – screen width equal to or greater than 768px)

  • .col-lg-

    (large devices – screen width equal to or greater than 992px)

  • .col-xl-

    (xlarge devices – screen width equal to or greater than 1200px)

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

sm

and

md

, you only need to specify

sm

.

Examples

The next chapters shows examples of grid systems for different devices and screen widths:

  • Stacked-to-horizontal
  • Extra Small Layout
  • Small devices
  • Medium devices
  • Large devices
  • Extra large devices
  • More grid examples

Bootstrap 4 | Grid System

Bootstrap Grid System allows up to 12 columns across the page. You can use each of them individually or merge them together for wider columns. All combinations of values summing up to 12 can be used.

Grid Classes: Bootstrap grid system contains five classes which are listed below:

  • .col- It is used for extra small screen devices (screen width less than 576px).
  • .col-sm- It is used for small screen devices (screen width greater than or equal to 576px).
  • .col-md- It is used for medium screen size devices (screen width greater than or equal to 768px).
  • .col-lg- It is used for large screen size devices (screen width greater than or equal to 992px).
  • .col-xl- It is used for xlarge screen size devices (screen width equal to or greater than 1200px).

Components of Grid System:

  • Containers: Bootstrap requires a containing element to wrap site contents in a grid system. The word container is used to contain the row elements and row elements containing the column elements.
  • Rows: Rows must be placed within the container or container-fluid for proper alignment and padding. Rows are used to create horizontal groups of columns.
  • Columns: Grid columns are created by specifying the number of twelve available columns you wish to span. For example, three equal columns would use three col-lg-4.

Example 1: This example uses bootstrap to create an equal width column grid on all devices and screen widths.

Output:

Example 2: This example uses bootstrap to create equal width responsive column grid. When the screen size is less than 576px the column automatically stack to each other.

Output:

  • Run-on large screen (Desktop, tablets):
  • Run-on small screen (mobile):

Example 3: This example uses bootstrap to create unequal width responsive column grid. When the screen size is less than 576px the column automatically stack to each other.

Output:

  • Run-on large screen (Desktop, tablets):
  • Run-on small screen (mobile):

Supported Browser:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!

Last Updated :
28 Apr, 2022

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Bootstrap Grid System

Bootstrap Grid System The Complete Guide - In Action
Bootstrap Grid System The Complete Guide – In Action

Grid Options

The following table summarizes aspects of how Bootstrap 4 grid system works across multiple devices −

Extra small devices (<576px) Small devices (≥576px) Medium devices (≥768px) Large devices (≥992px) Extra Large devices (≥1200px)
Grid behavior Horizontal at all times Collapsed to start, horizontal above breakpoints Collapsed to start, horizontal above breakpoints Collapsed to start, horizontal above breakpoints Collapsed to start, horizontal above breakpoints
Max container width None (auto) 540px 720px 960px 1140px
Class classes .col- .col-sm- .col-md- .col-lg- .col-xl-
# of columns 12 12 12 12 12
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)

30px

(15px on each side of a column)

Nestable Yes Yes Yes Yes Yes
Column ordering Yes Yes Yes Yes Yes

Basic Grid Structure

Following is basic structure of Bootstrap 4 grid −

Creating Three Column Layouts

The following example describes creating three column layouts for medium and large devices. If the screen resolution is more than or equal to 992 pixels, then it will display in landscape mode in tablets and as usual, it will display in portrait mode.

Example



<br /> Bootstrap 4 Example<br />

.col-sm-4
.col-sm-4
.col-sm-4
.col-sm-3
.col-sm-4
.col-sm-5
.col-sm-2
.col-sm-8
.col-sm-2
.col-sm-2
.col-sm-3
.col-sm-7



It will produce the following result −

Bootstrap Grid System Tutorial | Bootstrap 5
Bootstrap Grid System Tutorial | Bootstrap 5

Creating Two Column Layouts

The following example describes creating two column layouts for small, medium and large devices. On small devices such as mobile phones, columns will automatically become horizontal as default.

Example



<br /> Bootstrap 4 Example<br />

.col-sm-6
.col-sm-6
.col-sm-7
.col-sm-5
.col-sm-4
.col-sm-8
.col-sm-9
.col-sm-3



It will produce the following result −

Output

Grid Classes

The Bootstrap 4 grid system has five classes:


  • .col-

    (extra small devices – screen width less than 576px)

  • .col-sm-

    (small devices – screen width equal to or greater than 576px)

  • .col-md-

    (medium devices – screen width equal to or greater than 768px)

  • .col-lg-

    (large devices – screen width equal to or greater than 992px)

  • .col-xl-

    (xlarge devices – screen width equal to or greater than 1200px)

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

sm

and

md

, you only need to specify

sm

.

Bootstrap 5 Grid System Tutorial
Bootstrap 5 Grid System Tutorial

Basic Structure of a Bootstrap 4 Grid

The following is a basic structure of a Bootstrap 4 grid:

First example: create a row (). Then, add the desired number of columns (tags with appropriate

.col-*-*

classes). The first star (*)
represents the responsiveness: sm, md, lg or xl, while the second star
represents a number, which should add up to 12 for each row.

Second example: instead of adding a number to each

col

, let bootstrap handle
the layout, to create equal width columns: two

"col"

elements = 50% width to
each col. three cols = 33.33% width to each col. four cols = 25% width, etc. You
can also use

.col-sm|md|lg|xl

to make the columns responsive.

Below we have collected some examples of basic Bootstrap 4 grid layouts.

How it works

Breaking it down, here’s how the grid system comes together:

  • Our grid supports six responsive breakpoints. Breakpoints are based on


    min-width

    media queries, meaning they affect that breakpoint and all those above it (e.g.,

    .col-sm-4

    applies to

    sm

    ,

    md

    ,

    lg

    ,

    xl

    , and

    xxl

    ). This means you can control container and column sizing and behavior by each breakpoint.

  • Containers center and horizontally pad your content. Use


    .container

    for a responsive pixel width,

    .container-fluid

    for

    width: 100%

    across all viewports and devices, or a responsive container (e.g.,

    .container-md

    ) for a combination of fluid and pixel widths.

  • 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 to ensure the content in your columns is visually aligned down the left side. Rows also support modifier classes to uniformly apply column sizing and gutter classes to change the spacing of your content.

  • Columns are incredibly flexible. There are 12 template columns available per row, allowing you to create different combinations of elements that span any number of columns. Column classes indicate the number of template columns to span (e.g.,


    col-4

    spans four).

    width

    s are set in percentages so you always have the same relative sizing.

  • Gutters are also responsive and customizable. Gutter classes are available across all breakpoints, with all the same sizes as our margin and padding spacing. Change horizontal gutters with


    .gx-*

    classes, vertical gutters with

    .gy-*

    , or all gutters with

    .g-*

    classes.

    .g-0

    is also available to remove gutters.

  • Sass variables, maps, and mixins power the grid. If you don’t want to use the predefined grid classes in Bootstrap, you can use our grid’s source Sass to create your own with more semantic markup. We also include some CSS custom properties to consume these Sass variables for even greater flexibility for you.

Be aware of the limitations and bugs around flexbox, like the inability to use some HTML elements as flex containers.

Bootstrap 4 Grid System Explained!
Bootstrap 4 Grid System Explained!

Example

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 explanation for how the grid system comes together.

Column
Column
Column

The above example creates three equal-width columns across all devices and viewports using our predefined grid classes. Those columns are centered in the page with the parent

.container

.

Responsive Columns

The following example shows how to create four equal-width columns starting at tablets and scaling to extra large desktops. On mobile phones or screens that are less than 576px wide, the columns will automatically stack on top of each other:

Example

.col-sm-3

.col-sm-3

.col-sm-3

.col-sm-3

Using the Bootstrap 4 Grid  | BOOTSTRAP 4 TUTORIAL
Using the Bootstrap 4 Grid | BOOTSTRAP 4 TUTORIAL

Basic Structure of a Bootstrap 4 Grid

The following is a basic structure of a Bootstrap 4 grid:

First example: create a row (). Then, add the desired number of columns (tags with appropriate

.col-*-*

classes). The first star (*)
represents the responsiveness: sm, md, lg or xl, while the second star
represents a number, which should always add up to 12 for each row.

Second example: instead of adding a number to each

col

, let bootstrap handle
the layout, to create equal width columns: two

"col"

elements = 50% width to
each col. three cols = 33.33% width to each col. four cols = 25% width, etc. You
can also use

.col-sm|md|lg|xl

to make the columns responsive.

Grid options

Bootstrap’s grid system can adapt across all six default breakpoints, and any breakpoints you customize. The six default grid tiers are as follow:

  • Extra small (xs)
  • Small (sm)
  • Medium (md)
  • Large (lg)
  • Extra large (xl)
  • Extra extra large (xxl)

As noted above, each of these breakpoints have their own container, unique class prefix, and modifiers. Here’s how the grid changes across these breakpoints:

xs

<576px

sm

≥576px

md

≥768px

lg

≥992px

xl

≥1200px

xxl

≥1400px

Container None (auto) 540px 720px 960px 1140px 1320px
Class prefix
# of columns 12
Gutter width 1.5rem (.75rem on left and right)
Custom gutters Yes
Nestable Yes
Column ordering Yes
Responsive website với Bootstrap cực chi tiết - Cách sử dụng Grid system của bootstrap
Responsive website với Bootstrap cực chi tiết – Cách sử dụng Grid system của bootstrap

Sass

When using Bootstrap’s source Sass files, you have the option of using Sass variables and mixins to create custom, semantic, and responsive page layouts. Our predefined grid classes use these same variables and mixins to provide a whole suite of ready-to-use classes for fast responsive layouts.

Variables

Variables and maps determine the number of columns, the gutter width, and the media query point at which to begin floating columns. We use these to generate the predefined grid classes documented above, as well as for the custom mixins listed below.


$grid-columns: 12; $grid-gutter-width: 1.5rem;


$grid-breakpoints: ( xs: 0, sm: 576px, md: 768px, lg: 992px, xl: 1200px, xxl: 1400px );


$container-max-widths: ( sm: 540px, md: 720px, lg: 960px, xl: 1140px, xxl: 1320px );

Mixins

Mixins are used in conjunction with the grid variables to generate semantic CSS for individual grid columns.


// Creates a wrapper for a series of columns @include make-row(); // Make the element grid-ready (applying everything but the width) @include make-col-ready(); // Without optional size values, the mixin will create equal columns (similar to using .col) @include make-col(); @include make-col($size, $columns: $grid-columns); // Get fancy by offsetting, or changing the sort order @include make-col-offset($size, $columns: $grid-columns);

Example usage

You can modify the variables to your own custom values, or just use the mixins with their default values. Here’s an example of using the default settings to create a two-column layout with a gap between.


.example-container { @include make-container(); // Make sure to define this width after the mixin to override // `width: 100%` generated by `make-container()` width: 800px; } .example-row { @include make-row(); } .example-content-main { @include make-col-ready(); @include media-breakpoint-up(sm) { @include make-col(6); } @include media-breakpoint-up(lg) { @include make-col(8); } } .example-content-secondary { @include make-col-ready(); @include media-breakpoint-up(sm) { @include make-col(6); } @include media-breakpoint-up(lg) { @include make-col(4); } }

Main content
Secondary content

Reordering

Order classes

Use

.order-

classes for controlling the visual order of your content. These classes are responsive, so you can set the

order

by breakpoint (e.g.,

.order-1.order-md-2

). Includes support for through

12

across all five grid tiers.

First, but unordered
Second, but last
Third, but first

There are also responsive

.order-first

and

.order-last

classes that change the

order

of an element by applying

order: -1

and

order: 13

(

order: $columns + 1

), respectively. These classes can also be intermixed with the numbered

.order-*

classes as needed.

First, but last
Second, but unordered
Third, but first

Offsetting columns

You can offset grid columns in two ways: our responsive

.offset-

grid classes and our margin utilities. Grid classes are sized to match columns while margins are more useful for quick layouts where the width of the offset is variable.

Offset classes

Move columns to the right using

.offset-md-*

classes. These classes increase the left margin of a column by columns. For example,

.offset-md-4

moves

.col-md-4

over four columns.

.col-md-4
.col-md-4 .offset-md-4
.col-md-3 .offset-md-3
.col-md-3 .offset-md-3
.col-md-6 .offset-md-3

In addition to column clearing at responsive breakpoints, you may need to reset offsets. See this in action in the grid example.

.col-sm-5 .col-md-6
.col-sm-5 .offset-sm-2 .col-md-6 .offset-md-0
.col-sm-6 .col-md-5 .col-lg-6
.col-sm-6 .col-md-5 .offset-md-2 .col-lg-6 .offset-lg-0

Margin utilities

With the move to flexbox in v4, you can use margin utilities like

.mr-auto

to force sibling columns away from one another.

.col-md-4
.col-md-4 .ml-auto
.col-md-3 .ml-md-auto
.col-md-3 .ml-md-auto
.col-auto .mr-auto
.col-auto

Bootstrap - Grid Layout | Web Development Course | Lecture 16
Bootstrap – Grid Layout | Web Development Course | Lecture 16

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.

One of three columns
One of three columns
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.

Be aware of the limitations and bugs around flexbox, like the inability to use some HTML elements as flex containers.

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

<576px

Small

≥576px

Medium

≥768px

Large

≥992px

Extra large

≥1200px

Max container width None (auto) 540px 720px 960px 1140px
Class prefix
# of columns 12
Gutter width 30px (15px on each side of a column)
Nestable Yes
Column ordering Yes
Responsive layout với CSS Grid
Responsive layout với CSS Grid

Sass mixins

When using Bootstrap’s source Sass files, you have the option of using Sass variables and mixins to create custom, semantic, and responsive page layouts. Our predefined grid classes use these same variables and mixins to provide a whole suite of ready-to-use classes for fast responsive layouts.

Variables

Variables and maps determine the number of columns, the gutter width, and the media query point at which to begin floating columns. We use these to generate the predefined grid classes documented above, as well as for the custom mixins listed below.


$grid-columns: 12; $grid-gutter-width: 30px; $grid-breakpoints: ( // Extra small screen / phone xs: 0, // Small screen / phone sm: 576px, // Medium screen / tablet md: 768px, // Large screen / desktop lg: 992px, // Extra large screen / wide desktop xl: 1200px ); $container-max-widths: ( sm: 540px, md: 720px, lg: 960px, xl: 1140px );

Mixins

Mixins are used in conjunction with the grid variables to generate semantic CSS for individual grid columns.


// Creates a wrapper for a series of columns @include make-row(); // Make the element grid-ready (applying everything but the width) @include make-col-ready(); @include make-col($size, $columns: $grid-columns); // Get fancy by offsetting, or changing the sort order @include make-col-offset($size, $columns: $grid-columns);

Example usage

You can modify the variables to your own custom values, or just use the mixins with their default values. Here’s an example of using the default settings to create a two-column layout with a gap between.


.example-container { width: 800px; @include make-container(); } .example-row { @include make-row(); } .example-content-main { @include make-col-ready(); @include media-breakpoint-up(sm) { @include make-col(6); } @include media-breakpoint-up(lg) { @include make-col(8); } } .example-content-secondary { @include make-col-ready(); @include media-breakpoint-up(sm) { @include make-col(6); } @include media-breakpoint-up(lg) { @include make-col(4); } }

Main content
Secondary content

Responsive breakpoints

Since Bootstrap is developed to be mobile first, we use a handful of media queries to create sensible breakpoints for our layouts and interfaces. These breakpoints are mostly based on minimum viewport widths and allow us to scale up elements as the viewport changes.

Bootstrap primarily uses the following media query ranges—or breakpoints—in our source Sass files for our layout, grid system, and components.


// Extra small devices (portrait phones, less than 576px) // No media query since this is the default in Bootstrap // Small devices (landscape phones, 576px and up) @media (min-width: 576px) { ... } // Medium devices (tablets, 768px and up) @media (min-width: 768px) { ... } // Large devices (desktops, 992px and up) @media (min-width: 992px) { ... } // Extra large devices (large desktops, 1200px and up) @media (min-width: 1200px) { ... }

Since we write our source CSS in Sass, all our media queries are available via Sass mixins:


@include media-breakpoint-up(xs) { ... } @include media-breakpoint-up(sm) { ... } @include media-breakpoint-up(md) { ... } @include media-breakpoint-up(lg) { ... } @include media-breakpoint-up(xl) { ... } // Example usage: @include media-breakpoint-up(sm) { .some-class { display: block; } }

We occasionally use media queries that go in the other direction (the given screen size or smaller):


// Extra small devices (portrait phones, less than 576px) @media (max-width: 575.98px) { ... } // Small devices (landscape phones, less than 768px) @media (max-width: 767.98px) { ... } // Medium devices (tablets, less than 992px) @media (max-width: 991.98px) { ... } // Large devices (desktops, less than 1200px) @media (max-width: 1199.98px) { ... } // Extra large devices (large desktops) // No media query since the extra-large breakpoint has no upper bound on its width

Note that since browsers do not currently support range context queries, we work around the limitations of

min-

and

max-

prefixes and viewports with fractional widths (which can occur under certain conditions on high-dpi devices, for instance) by using values with higher precision for these comparisons.

Once again, these media queries are also available via Sass mixins:


@include media-breakpoint-down(xs) { ... } @include media-breakpoint-down(sm) { ... } @include media-breakpoint-down(md) { ... } @include media-breakpoint-down(lg) { ... }

There are also media queries and mixins for targeting a single segment of screen sizes using the minimum and maximum breakpoint widths.


// Extra small devices (portrait phones, less than 576px) @media (max-width: 575.98px) { ... } // Small devices (landscape phones, 576px and up) @media (min-width: 576px) and (max-width: 767.98px) { ... } // Medium devices (tablets, 768px and up) @media (min-width: 768px) and (max-width: 991.98px) { ... } // Large devices (desktops, 992px and up) @media (min-width: 992px) and (max-width: 1199.98px) { ... } // Extra large devices (large desktops, 1200px and up) @media (min-width: 1200px) { ... }

These media queries are also available via Sass mixins:


@include media-breakpoint-only(xs) { ... } @include media-breakpoint-only(sm) { ... } @include media-breakpoint-only(md) { ... } @include media-breakpoint-only(lg) { ... } @include media-breakpoint-only(xl) { ... }

Similarly, media queries may span multiple breakpoint widths:


// Example // Apply styles starting from medium devices and up to extra large devices @media (min-width: 768px) and (max-width: 1199.98px) { ... }

The Sass mixin for targeting the same screen size range would be:


@include media-breakpoint-between(md, xl) { ... }

Bootstrap 5 - Responsive Blog Posts Grid Layout
Bootstrap 5 – Responsive Blog Posts Grid Layout

Examples

The next chapters shows examples of grid systems for different devices and screen widths:

  • Stacked-to-horizontal
  • Extra Small Layout
  • Small devices
  • Medium devices
  • Large devices
  • Extra large devices
  • More grid examples

Bootstrap 4 Grids

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.

Create a Data Table in Bootstrap 5 (2023)
Create a Data Table in Bootstrap 5 (2023)

Working of Grid System

  • Rows must be placed within a .container class for proper alignment and padding.

  • For responsive width use .container class and for fixed width across all viewport, use the .container-fluid class.

  • Use rows to create horizontal groups of columns.

  • Content should be placed within the columns, and only columns may be the immediate children of rows.

  • Columns contain padding for controlling the space between them.

  • If you place more than 12 columns in a row, then the columns will be placed in a new line.

  • Columns create gaps between column content via padding. Therefore, you can remove the margin from rows and padding from columns with .no-gutters class on the row.

  • You can make grid system responsive by using five grid breakpoints such as extra small, small, medium, large, and extra large.

  • Predefined grid classes like .col-4 are available for quickly making grid layouts. LESS mixins can also be used for more semantic layouts.

Phần kết

Như vậy trong bài viết nay chúng ta đã cùng tìm hiểu về Grid System trong Bootstrap, đây là một tính năng vô cùng mạnh mẽ của Bootstrap nên nếu làm chủ được nó thì công việc xây dựng bố cục cũng như phát triển web Front-end sẽ trở nên dễ dàng hơn rất nhiều. Rất mong rằng bài viết này sẽ giúp ích cho các bạn

Tài liệu tham khảo:
https://getbootstrap.com/

All rights reserved

Overview

Components and options for laying out your Bootstrap project, including wrapping containers, a powerful grid system, a flexible media object, and responsive utility classes.

#06 - Bootstrap Grids - (தமிழில்) (Tamil) | Bootstrap Course  | Web Design
#06 – Bootstrap Grids – (தமிழில்) (Tamil) | Bootstrap Course | Web Design

Bootstrap heading Secondary text

Bootstrap heading Secondary text

Bootstrap heading Secondary text
Bootstrap heading Secondary text
Bootstrap heading Secondary text

Bootstrap’s global default

font-size

is 14px, with a

line-height

of 1.428. This is applied to the and all paragraphs. In addition, (paragraphs) receive a bottom margin of half their computed line-height (10px by default).

Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula.

Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Donec ullamcorper nulla non metus auctor fringilla.

Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.

...

Make a paragraph stand out by adding

.lead

.

Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Duis mollis, est non commodo luctus.

...

The typographic scale is based on two Less variables in variables.less:

@font-size-base

and

@line-height-base

. The first is the base font-size used throughout and the second is the base line-height. We use those variables and some simple math to create the margins, paddings, and line-heights of all our type and more. Customize them and Bootstrap adapts.

For highlighting a run of text due to its relevance in another context, use the tag.

You can use the mark tag to highlight text.


You can use the mark tag to

highlight

text.

For indicating blocks of text that have been deleted use the tag.


This line of text is meant to be treated as deleted text.



This line of text is meant to be treated as deleted text.

For indicating blocks of text that are no longer relevant use the tag.


This line of text is meant to be treated as no longer accurate.



This line of text is meant to be treated as no longer accurate.

For indicating additions to the document use the tag.



This line of text is meant to be treated as an addition to the document.

To underline text use the tag.

This line of text will render as underlined



This line of text will render as underlined

Make use of HTML’s default emphasis tags with lightweight styles.

For de-emphasizing inline or blocks of text, use the tag to set text at 85% the size of the parent. Heading elements receive their own

font-size

for nested elements.

You may alternatively use an inline element with

.small

in place of any .

This line of text is meant to be treated as fine print.



This line of text is meant to be treated as fine print.

For emphasizing a snippet of text with a heavier font-weight.

The following snippet of text is rendered as bold text.



rendered as bold text

For emphasizing a snippet of text with italics.

The following snippet of text is rendered as italicized text.



rendered as italicized text

Feel free to use and in HTML5. is meant to highlight words or phrases without conveying additional importance while is mostly for voice, technical terms, etc.

Easily realign text to components with text alignment classes.

Left aligned text.

Center aligned text.

Right aligned text.

Justified text.

No wrap text.

Left aligned text.

Center aligned text.

Right aligned text.

Justified text.

No wrap text.

Transform text in components with text capitalization classes.

Lowercased text.

Uppercased text.

Capitalized text.

Lowercased text.

Uppercased text.

Capitalized text.

Stylized implementation of HTML’s element for abbreviations and acronyms to show the expanded version on hover. Abbreviations with a

title

attribute have a light dotted bottom border and a help cursor on hover, providing additional context on hover and to users of assistive technologies.

An abbreviation of the word attribute is attr.



attr

Add

.initialism

to an abbreviation for a slightly smaller font-size.

HTML is the best thing since sliced bread.



HTML

Present contact information for the nearest ancestor or the entire body of work. Preserve formatting by ending all lines with .


Twitter, Inc.

1355 Market Street, Suite 900 San Francisco, CA 94103

P:

(123) 456-7890

Full Name


[email protected]

For quoting blocks of content from another source within your document.

Wrap around any HTML as the quote. For straight quotes, we recommend a .

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

Style and content changes for simple variations on a standard .

Add a for identifying the source. Wrap the name of the source work in .

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

Someone famous in

Source Title

Add

.blockquote-reverse

for a blockquote with right-aligned content.

...

A list of items in which the order does not explicitly matter.

  • ...

A list of items in which the order does explicitly matter.

  1. ...

Remove the default

list-style

and left margin on list items (immediate children only). This only applies to immediate children list items, meaning you will need to add the class for any nested lists as well.

  • ...

Place all list items on a single line with

display: inline-block;

and some light padding.

  • ...

A list of terms with their associated descriptions.

...
...

Make terms and descriptions in line up side-by-side. Starts off stacked like default s, but when the navbar expands, so do these.

...
...

Horizontal description lists will truncate terms that are too long to fit in the left column with

text-overflow

. In narrower viewports, they will change to the default stacked layout.

Wrap inline snippets of code with

should be wrapped as inline.


For example,

<section>

should be wrapped as inline.

Use the to indicate input that is typically entered via keyboard.


To switch directories, type

cd

followed by the name of the directory. To edit settings, press


ctrl

+

Use for multiple lines of code. Be sure to escape any angle brackets in the code for proper rendering.

Sample text here…

<p>Sample text here...</p>

You may optionally add the

.pre-scrollable

class, which will set a max-height of 350px and provide a y-axis scrollbar.

For indicating variables use the tag.

y = mx + b


= +

For indicating blocks sample output from a program use the tag.

This text is meant to be treated as sample output from a computer program.



This text is meant to be treated as sample output from a computer program.

For basic styling—light padding and only horizontal dividers—add the base class

.table

to any . It may seem super redundant, but given the widespread use of tables for other plugins like calendars and date pickers, we’ve opted to isolate our custom table styles.

First Name Last Name Username
Mark Otto @mdo
Jacob Thornton @fat
Larry the Bird

...

Use

.table-striped

to add zebra-striping to any table row within the .

Striped tables are styled via the

:nth-child

CSS selector, which is not available in Internet Explorer 8.

First Name Last Name Username
Mark Otto @mdo
Jacob Thornton @fat
Larry the Bird

...

Add

.table-bordered

for borders on all sides of the table and cells.

First Name Last Name Username
Mark Otto @mdo
Jacob Thornton @fat
Larry the Bird

...

Add

.table-hover

to enable a hover state on table rows within a .

First Name Last Name Username
Mark Otto @mdo
Jacob Thornton @fat
Larry the Bird

...

Add

.table-condensed

to make tables more compact by cutting cell padding in half.

First Name Last Name Username
Mark Otto @mdo
Jacob Thornton @fat
Larry the Bird

...

Use contextual classes to color table rows or individual cells.

Class Description
Applies the hover color to a particular row or cell
Indicates a successful or positive action
Indicates a neutral informative change or action
Indicates a warning that might need attention
Indicates a dangerous or potentially negative action
Column heading Column heading Column heading
Column content Column content Column content
Column content Column content Column content
Column content Column content Column content
Column content Column content Column content
Column content Column content Column content
Column content Column content Column content
Column content Column content Column content
Column content Column content Column content
Column content Column content Column content


...
...
...
...
...

... ... ... ... ...

Using color to add meaning to a table row or individual cell only provides a visual indication, which will not be conveyed to users of assistive technologies – such as screen readers. Ensure that information denoted by the color is either obvious from the content itself (the visible text in the relevant table row/cell), or is included through alternative means, such as additional text hidden with the

.sr-only

class.

Create responsive tables by wrapping any

.table

in

.table-responsive

to make them scroll horizontally on small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables.

Responsive tables make use of

overflow-y: hidden

, which clips off any content that goes beyond the bottom or top edges of the table. In particular, this can clip off dropdown menus and other third-party widgets.

Firefox has some awkward fieldset styling involving

width

that interferes with the responsive table. This cannot be overridden without a Firefox-specific hack that we don’t provide in Bootstrap:


@-moz-document url-prefix() { fieldset { display: table-cell; } }

For more information, read this Stack Overflow answer.

Table heading Table heading Table heading Table heading Table heading Table heading
Table cell Table cell Table cell Table cell Table cell Table cell
Table cell Table cell Table cell Table cell Table cell Table cell
Table cell Table cell Table cell Table cell Table cell Table cell
Table heading Table heading Table heading Table heading Table heading Table heading
Table cell Table cell Table cell Table cell Table cell Table cell
Table cell Table cell Table cell Table cell Table cell Table cell
Table cell Table cell Table cell Table cell Table cell Table cell

...

Individual form controls automatically receive some global styling. All textual , , and elements with

.form-control

are set to

width: 100%;

by default. Wrap labels and controls in

.form-group

for optimum spacing.

Example block-level help text here.


Do not mix form groups directly with input groups. Instead, nest the input group inside of the form group.

Add

.form-inline

to your form (which doesn’t have to be a ) for left-aligned and inline-block controls. This only applies to forms within viewports that are at least 768px wide.

Inputs and selects have

width: 100%;

applied by default in Bootstrap. Within inline forms, we reset that to

width: auto;

so multiple controls can reside on the same line. Depending on your layout, additional custom widths may be required.

Screen readers will have trouble with your forms if you don’t include a label for every input. For these inline forms, you can hide the labels using the

.sr-only

class. There are further alternative methods of providing a label for assistive technologies, such as the

aria-label

,

aria-labelledby

or

title

attribute. If none of these is present, screen readers may resort to using the

placeholder

attribute, if present, but note that use of

placeholder

as a replacement for other labelling methods is not advised.



.00


Use Bootstrap’s predefined grid classes to align labels and groups of form controls in a horizontal layout by adding

.form-horizontal

to the form (which doesn’t have to be a ). Doing so changes

.form-group

s to behave as grid rows, so no need for

.row

.

Examples of standard form controls supported in an example form layout.

Most common form control, text-based input fields. Includes support for all HTML5 types:

text

,

password

,

datetime

,

datetime-local

,

date

,

month

,

time

,

week

,

number

,

url

,

search

,

tel

, and

color

.

Inputs will only be fully styled if their

type

is properly declared.

To add integrated text or buttons before and/or after any text-based , check out the input group component.

Form control which supports multiple lines of text. Change

rows

attribute as necessary.

Checkboxes are for selecting one or several options in a list, while radios are for selecting one option from many.

Disabled checkboxes and radios are supported, but to provide a “not-allowed” cursor on hover of the parent , you’ll need to add the

.disabled

class to the parent

.radio

,

.radio-inline

,

.checkbox

, or

.checkbox-inline

.

Use the

.checkbox-inline

or

.radio-inline

classes on a series of checkboxes or radios for controls that appear on the same line.


Should you have no text within the , the input is positioned as you’d expect. Currently only works on non-inline checkboxes and radios. Remember to still provide some form of label for assistive technologies (for instance, using

aria-label

).

Note that many native select menus—namely in Safari and Chrome—have rounded corners that cannot be modified via

border-radius

properties.



For controls with the

multiple

attribute, multiple options are shown by default.



When you need to place plain text next to a form label within a form, use the

.form-control-static

class on a .


We remove the default

outline

styles on some form controls and apply a

box-shadow

in its place for

:focus

.


:focusstate

The above example input uses custom styles in our documentation to demonstrate the

:focus

state on a

.form-control

.

Add the

disabled

boolean attribute on an input to prevent user interactions. Disabled inputs appear lighter and add a

not-allowed

cursor.

Add the

disabled

attribute to a to disable all the controls within the at once.

By default, browsers will treat all native form controls (, and elements) inside a as disabled, preventing both keyboard and mouse interactions on them. However, if your form also includes elements, these will only be given a style of

pointer-events: none

. As noted in the section about disabled state for buttons (and specifically in the sub-section for anchor elements), this CSS property is not yet standardized and isn’t fully supported in Opera 18 and below, or in Internet Explorer 11, and won’t prevent keyboard users from being able to focus or activate these links. So to be safe, use custom JavaScript to disable such links.

While Bootstrap will apply these styles in all browsers, Internet Explorer 11 and below don’t fully support the

disabled

attribute on a . Use custom JavaScript to disable the fieldset in these browsers.



Add the

readonly

boolean attribute on an input to prevent modification of the input’s value. Read-only inputs appear lighter (just like disabled inputs), but retain the standard cursor.

Block level help text for form controls.

Help text should be explicitly associated with the form control it relates to using the

aria-describedby

attribute. This will ensure that assistive technologies – such as screen readers – will announce this help text when the user focuses or enters the control.



...

A block of help text that breaks onto a new line and may extend beyond one line.

Bootstrap includes validation styles for error, warning, and success states on form controls. To use, add

.has-warning

,

.has-error

, or

.has-success

to the parent element. Any

.control-label

,

.form-control

, and

.help-block

within that element will receive the validation styles.

Using these validation styles to denote the state of a form control only provides a visual, color-based indication, which will not be conveyed to users of assistive technologies – such as screen readers – or to colorblind users.

Ensure that an alternative indication of state is also provided. For instance, you can include a hint about state in the form control’s text itself (as is the case in the following code example), include a Glyphicon (with appropriate alternative text using the

.sr-only

class – see the Glyphicon examples), or by providing an additional help text block. Specifically for assistive technologies, invalid form controls can also be assigned an

aria-invalid="true"

attribute.



A block of help text that breaks onto a new line and may extend beyond one line.

You can also add optional feedback icons with the addition of

.has-feedback

and the right icon.

Feedback icons only work with textual elements.

Manual positioning of feedback icons is required for inputs without a label and for input groups with an add-on on the right. You are strongly encouraged to provide labels for all inputs for accessibility reasons. If you wish to prevent labels from being displayed, hide them with the

.sr-only

class. If you must do without labels, adjust the

top

value of the feedback icon. For input groups, adjust the

right

value to an appropriate pixel value depending on the width of your addon.

To ensure that assistive technologies – such as screen readers – correctly convey the meaning of an icon, additional hidden text should be included with the

.sr-only

class and explicitly associated with the form control it relates to using

aria-describedby

. Alternatively, ensure that the meaning (for instance, the fact that there is a warning for a particular text entry field) is conveyed in some other form, such as changing the text of the actual associated with the form control.

Although the following examples already mention the validation state of their respective form controls in the text itself, the above technique (using

.sr-only

text and

aria-describedby

) has been included for illustrative purposes.



(success)


(warning)


(error)


(success)


(success)


(success)



(success)


(success)


.sr-onlylabels

If you use the

.sr-only

class to hide a form control’s (rather than using other labelling options, such as the

aria-label

attribute), Bootstrap will automatically adjust the position of the icon once it’s been added.



(success)


(success)

Set heights using classes like

.input-lg

, and set widths using grid column classes like

.col-lg-*

.

Create taller or shorter form controls that match button sizes.





Quickly size labels and form controls within

.form-horizontal

by adding

.form-group-lg

or

.form-group-sm

.

Wrap inputs in grid columns, or any custom parent element, to easily enforce desired widths.

Use the button classes on an , , or element.



Link


Use any of the available button classes to quickly create a styled button.
















Fancy larger or smaller buttons? Add

.btn-lg

,

.btn-sm

, or

.btn-xs

for additional sizes.





Create block level buttons—those that span the full width of a parent— by adding

.btn-block

.




Buttons will appear pressed (with a darker background, darker border, and inset shadow) when active. For elements, this is done via

:active

. For elements, it’s done with

.active

. However, you may use

.active

on s (and include the

aria-pressed="true"

attribute) should you need to replicate the active state programmatically.

No need to add

:active

as it’s a pseudo-class, but if you need to force the same appearance, go ahead and add

.active

.




Add the

.active

class to buttons.



Primary link


Link

Make buttons look unclickable by fading them back with

opacity

.

Add the

disabled

attribute to buttons.




Add the

.disabled

class to buttons.



Primary link


Link

We use

.disabled

as a utility class here, similar to the common

.active

class, so no prefix is required.

Images in Bootstrap 3 can be made responsive-friendly via the addition of the

.img-responsive

class. This applies

max-width: 100%;

,

height: auto;

and

display: block;

to the image so that it scales nicely to the parent element.

To center images which use the

.img-responsive

class, use

.center-block

instead of

.text-center

. See the helper classes section for more details about

.center-block

usage.

In Internet Explorer 8-10, SVG images with

.img-responsive

are disproportionately sized. To fix this, add

width: 100% \9;

where necessary. Bootstrap doesn’t apply this automatically as it causes complications to other image formats.

Add classes to an element to easily style images in any project.

Keep in mind that Internet Explorer 8 lacks support for rounded corners.

Convey meaning through color with a handful of emphasis utility classes. These may also be applied to links and will darken on hover just like our default link styles.

Fusce dapibus, tellus ac cursus commodo, tortor mauris nibh.

Nullam id dolor id nibh ultricies vehicula ut id elit.

Duis mollis, est non commodo luctus, nisi erat porttitor ligula.

Maecenas sed diam eget risus varius blandit sit amet non magna.

Etiam porta sem malesuada magna mollis euismod.

Donec ullamcorper nulla non metus auctor fringilla.

...

...

...

...

...

...

Sometimes emphasis classes cannot be applied due to the specificity of another selector. In most cases, a sufficient workaround is to wrap your text in a with the class.

Using color to add meaning only provides a visual indication, which will not be conveyed to users of assistive technologies – such as screen readers. Ensure that information denoted by the color is either obvious from the content itself (the contextual colors are only used to reinforce meaning that is already present in the text/markup), or is included through alternative means, such as additional text hidden with the

.sr-only

class.

Similar to the contextual text color classes, easily set the background of an element to any contextual class. Anchor components will darken on hover, just like the text classes.

Nullam id dolor id nibh ultricies vehicula ut id elit.

Duis mollis, est non commodo luctus, nisi erat porttitor ligula.

Maecenas sed diam eget risus varius blandit sit amet non magna.

Etiam porta sem malesuada magna mollis euismod.

Donec ullamcorper nulla non metus auctor fringilla.

...

...

...

...

...

Sometimes contextual background classes cannot be applied due to the specificity of another selector. In some cases, a sufficient workaround is to wrap your element’s content in a with the class.

As with contextual colors, ensure that any meaning conveyed through color is also conveyed in a format that is not purely presentational.

Use the generic close icon for dismissing content like modals and alerts.

Use carets to indicate dropdown functionality and direction. Note that the default caret will reverse automatically in dropup menus.

Float an element to the left or right with a class.

!important

is included to avoid specificity issues. Classes can also be used as mixins.

...
...


// Classes .pull-left { float: left !important; } .pull-right { float: right !important; } // Usage as mixins .element { .pull-left(); } .another-element { .pull-right(); }

Set an element to

display: block

and center via

margin

. Available as a mixin and class.

...


// Class .center-block { display: block; margin-left: auto; margin-right: auto; } // Usage as a mixin .element { .center-block(); }

Easily clear

float

s by adding

.clearfix

to the parent element. Utilizes the micro clearfix as popularized by Nicolas Gallagher. Can also be used as a mixin.


...


// Mixin itself .clearfix() { &:before, &:after { content: " "; display: table; } &:after { clear: both; } } // Usage as a mixin .element { .clearfix(); }

Force an element to be shown or hidden (including for screen readers) with the use of

.show

and

.hidden

classes. These classes use

!important

to avoid specificity conflicts, just like the quick floats. They are only available for block level toggling. They can also be used as mixins.


.hide

is available, but it does not always affect screen readers and is deprecated as of v3.0.1. Use

.hidden

or

.sr-only

instead.

Furthermore,

.invisible

can be used to toggle only the visibility of an element, meaning its

display

is not modified and the element can still affect the flow of the document.

...
...


// Classes .show { display: block !important; } .hidden { display: none !important; } .invisible { visibility: hidden; } // Usage as mixins .element { .show(); } .another-element { .hidden(); }

Hide an element to all devices except screen readers with

.sr-only

. Combine

.sr-only

with

.sr-only-focusable

to show the element again when it’s focused (e.g. by a keyboard-only user). Necessary for following accessibility best practices. Can also be used as mixins.



Skip to main content


// Usage as a mixin .skip-navigation { .sr-only(); .sr-only-focusable(); }

Utilize the

.text-hide

class or mixin to help replace an element’s text content with a background image.

Custom heading


// Usage as a mixin .heading { .text-hide(); }

For faster mobile-friendly development, use these utility classes for showing and hiding content by device via media query. Also included are utility classes for toggling content when printed.

Try to use these on a limited basis and avoid creating entirely different versions of the same site. Instead, use them to complement each device’s presentation.

Use a single or combination of the available classes for toggling content across viewport breakpoints.

Extra small devices Phones (<768px) Small devices Tablets (≥768px) Medium devices Desktops (≥992px) Large devices Desktops (≥1200px)
Visible Hidden Hidden Hidden
Hidden Visible Hidden Hidden
Hidden Hidden Visible Hidden
Hidden Hidden Hidden Visible
Hidden Visible Visible Visible
Visible Hidden Visible Visible
Visible Visible Hidden Visible
Visible Visible Visible Hidden

As of v3.2.0, the

.visible-*-*

classes for each breakpoint come in three variations, one for each CSS

display

property value listed below.

Group of classes CSS

So, for extra small (

xs

) screens for example, the available

.visible-*-*

classes are:

.visible-xs-block

,

.visible-xs-inline

, and

.visible-xs-inline-block

.

The classes

.visible-xs

,

.visible-sm

,

.visible-md

, and

.visible-lg

also exist, but are deprecated as of v3.2.0. They are approximately equivalent to

.visible-*-block

, except with additional special cases for toggling -related elements.

Similar to the regular responsive classes, use these for toggling content for print.

Classes Browser
Hidden Visible
Visible Hidden

The class

.visible-print

also exists but is deprecated as of v3.2.0. It is approximately equivalent to

.visible-print-block

, except with additional special cases for -related elements.

Resize your browser or load on different devices to test the responsive utility classes.

Green checkmarks indicate the element is visible in your current viewport.

Here, green checkmarks also indicate the element is hidden in your current viewport.

Bootstrap’s CSS is built on Less, a preprocessor with additional functionality like variables, mixins, and functions for compiling CSS. Those looking to use the source Less files instead of our compiled CSS files can make use of the numerous variables and mixins we use throughout the framework.

Grid variables and mixins are covered within the Grid system section.

Bootstrap can be used in at least two ways: with the compiled CSS or with the source Less files. To compile the Less files, consult the Getting Started section for how to setup your development environment to run the necessary commands.

Third party compilation tools may work with Bootstrap, but they are not supported by our core team.

Variables are used throughout the entire project as a way to centralize and share commonly used values like colors, spacing, or font stacks. For a complete breakdown, please see the Customizer.

Easily make use of two color schemes: grayscale and semantic. Grayscale colors provide quick access to commonly used shades of black while semantic include various colors assigned to meaningful contextual values.


@gray-darker: lighten(#000, 13.5%); // #222 @gray-dark: lighten(#000, 20%); // #333 @gray: lighten(#000, 33.5%); // #555 @gray-light: lighten(#000, 46.7%); // #777 @gray-lighter: lighten(#000, 93.5%); // #eee


@brand-primary: darken(#428bca, 6.5%); // #337ab7 @brand-success: #5cb85c; @brand-info: #5bc0de; @brand-warning: #f0ad4e; @brand-danger: #d9534f;

Use any of these color variables as they are or reassign them to more meaningful variables for your project.


// Use as-is .masthead { background-color: @brand-primary; } // Reassigned variables in Less @alert-message-background: @brand-info; .alert { background-color: @alert-message-background; }

A handful of variables for quickly customizing key elements of your site’s skeleton.


// Scaffolding @body-bg: #fff; @text-color: @black-50;

Easily style your links with the right color with only one value.


// Variables @link-color: @brand-primary; @link-hover-color: darken(@link-color, 15%); // Usage a { color: @link-color; text-decoration: none; &:hover { color: @link-hover-color; text-decoration: underline; } }

Note that the

@link-hover-color

uses a function, another awesome tool from Less, to automagically create the right hover color. You can use

darken

,

lighten

,

saturate

, and

desaturate

.

Easily set your typeface, text size, leading, and more with a few quick variables. Bootstrap makes use of these as well to provide easy typographic mixins.


@font-family-sans-serif: "Helvetica Neue", Helvetica, Arial, sans-serif; @font-family-serif: Georgia, "Times New Roman", Times, serif; @font-family-monospace: Menlo, Monaco, Consolas, "Courier New", monospace; @font-family-base: @font-family-sans-serif; @font-size-base: 14px; @font-size-large: ceil((@font-size-base * 1.25)); // ~18px @font-size-small: ceil((@font-size-base * 0.85)); // ~12px @font-size-h1: floor((@font-size-base * 2.6)); // ~36px @font-size-h2: floor((@font-size-base * 2.15)); // ~30px @font-size-h3: ceil((@font-size-base * 1.7)); // ~24px @font-size-h4: ceil((@font-size-base * 1.25)); // ~18px @font-size-h5: @font-size-base; @font-size-h6: ceil((@font-size-base * 0.85)); // ~12px @line-height-base: 1.428571429; // 20/14 @line-height-computed: floor((@font-size-base * @line-height-base)); // ~20px @headings-font-family: inherit; @headings-font-weight: 500; @headings-line-height: 1.1; @headings-color: inherit;

Two quick variables for customizing the location and filename of your icons.


@icon-font-path: "../fonts/"; @icon-font-name: "glyphicons-halflings-regular";

Components throughout Bootstrap make use of some default variables for setting common values. Here are the most commonly used.


@padding-base-vertical: 6px; @padding-base-horizontal: 12px; @padding-large-vertical: 10px; @padding-large-horizontal: 16px; @padding-small-vertical: 5px; @padding-small-horizontal: 10px; @padding-xs-vertical: 1px; @padding-xs-horizontal: 5px; @line-height-large: 1.33; @line-height-small: 1.5; @border-radius-base: 4px; @border-radius-large: 6px; @border-radius-small: 3px; @component-active-color: #fff; @component-active-bg: @brand-primary; @caret-width-base: 4px; @caret-width-large: 5px;

Vendor mixins are mixins to help support multiple browsers by including all relevant vendor prefixes in your compiled CSS.

Reset your components’ box model with a single mixin. For context, see this helpful article from Mozilla.

The mixin is deprecated as of v3.2.0, with the introduction of Autoprefixer. To preserve backwards-compatibility, Bootstrap will continue to use the mixin internally until Bootstrap v4.


.box-sizing(@box-model) { -webkit-box-sizing: @box-model; // Safari <= 5 -moz-box-sizing: @box-model; // Firefox <= 19 box-sizing: @box-model; }

Today all modern browsers support the non-prefixed

border-radius

property. As such, there is no

.border-radius()

mixin, but Bootstrap does include shortcuts for quickly rounding two corners on a particular side of an object.


.border-top-radius(@radius) { border-top-right-radius: @radius; border-top-left-radius: @radius; } .border-right-radius(@radius) { border-bottom-right-radius: @radius; border-top-right-radius: @radius; } .border-bottom-radius(@radius) { border-bottom-right-radius: @radius; border-bottom-left-radius: @radius; } .border-left-radius(@radius) { border-bottom-left-radius: @radius; border-top-left-radius: @radius; }

If your target audience is using the latest and greatest browsers and devices, be sure to just use the

box-shadow

property on its own. If you need support for older Android (pre-v4) and iOS devices (pre-iOS 5), use the deprecated mixin to pick up the required

-webkit

prefix.

The mixin is deprecated as of v3.1.0, since Bootstrap doesn’t officially support the outdated platforms that don’t support the standard property. To preserve backwards-compatibility, Bootstrap will continue to use the mixin internally until Bootstrap v4.

Be sure to use

rgba()

colors in your box shadows so they blend as seamlessly as possible with backgrounds.


.box-shadow(@shadow: 0 1px 3px rgba(0,0,0,.25)) { -webkit-box-shadow: @shadow; // iOS <4.3 & Android <4.1 box-shadow: @shadow; }

Multiple mixins for flexibility. Set all transition information with one, or specify a separate delay and duration as needed.

The mixins are deprecated as of v3.2.0, with the introduction of Autoprefixer. To preserve backwards-compatibility, Bootstrap will continue to use the mixins internally until Bootstrap v4.


.transition(@transition) { -webkit-transition: @transition; transition: @transition; } .transition-property(@transition-property) { -webkit-transition-property: @transition-property; transition-property: @transition-property; } .transition-delay(@transition-delay) { -webkit-transition-delay: @transition-delay; transition-delay: @transition-delay; } .transition-duration(@transition-duration) { -webkit-transition-duration: @transition-duration; transition-duration: @transition-duration; } .transition-timing-function(@timing-function) { -webkit-transition-timing-function: @timing-function; transition-timing-function: @timing-function; } .transition-transform(@transition) { -webkit-transition: -webkit-transform @transition; -moz-transition: -moz-transform @transition; -o-transition: -o-transform @transition; transition: transform @transition; }

Rotate, scale, translate (move), or skew any object.

The mixins are deprecated as of v3.2.0, with the introduction of Autoprefixer. To preserve backwards-compatibility, Bootstrap will continue to use the mixins internally until Bootstrap v4.


.rotate(@degrees) { -webkit-transform: rotate(@degrees); -ms-transform: rotate(@degrees); // IE9 only transform: rotate(@degrees); } .scale(@ratio; @ratio-y...) { -webkit-transform: scale(@ratio, @ratio-y); -ms-transform: scale(@ratio, @ratio-y); // IE9 only transform: scale(@ratio, @ratio-y); } .translate(@x; @y) { -webkit-transform: translate(@x, @y); -ms-transform: translate(@x, @y); // IE9 only transform: translate(@x, @y); } .skew(@x; @y) { -webkit-transform: skew(@x, @y); -ms-transform: skewX(@x) skewY(@y); // See https://github.com/twbs/bootstrap/issues/4885; IE9+ transform: skew(@x, @y); } .translate3d(@x; @y; @z) { -webkit-transform: translate3d(@x, @y, @z); transform: translate3d(@x, @y, @z); } .rotateX(@degrees) { -webkit-transform: rotateX(@degrees); -ms-transform: rotateX(@degrees); // IE9 only transform: rotateX(@degrees); } .rotateY(@degrees) { -webkit-transform: rotateY(@degrees); -ms-transform: rotateY(@degrees); // IE9 only transform: rotateY(@degrees); } .perspective(@perspective) { -webkit-perspective: @perspective; -moz-perspective: @perspective; perspective: @perspective; } .perspective-origin(@perspective) { -webkit-perspective-origin: @perspective; -moz-perspective-origin: @perspective; perspective-origin: @perspective; } .transform-origin(@origin) { -webkit-transform-origin: @origin; -moz-transform-origin: @origin; -ms-transform-origin: @origin; // IE9 only transform-origin: @origin; }

A single mixin for using all of CSS3’s animation properties in one declaration and other mixins for individual properties.

The mixins are deprecated as of v3.2.0, with the introduction of Autoprefixer. To preserve backwards-compatibility, Bootstrap will continue to use the mixins internally until Bootstrap v4.


.animation(@animation) { -webkit-animation: @animation; animation: @animation; } .animation-name(@name) { -webkit-animation-name: @name; animation-name: @name; } .animation-duration(@duration) { -webkit-animation-duration: @duration; animation-duration: @duration; } .animation-timing-function(@timing-function) { -webkit-animation-timing-function: @timing-function; animation-timing-function: @timing-function; } .animation-delay(@delay) { -webkit-animation-delay: @delay; animation-delay: @delay; } .animation-iteration-count(@iteration-count) { -webkit-animation-iteration-count: @iteration-count; animation-iteration-count: @iteration-count; } .animation-direction(@direction) { -webkit-animation-direction: @direction; animation-direction: @direction; }

Set the opacity for all browsers and provide a

filter

fallback for IE8.


.opacity(@opacity) { opacity: @opacity; // IE8 filter @opacity-ie: (@opacity * 100); filter: ~"alpha(opacity=@{opacity-ie})"; }

Provide context for form controls within each field.


.placeholder(@color: @input-color-placeholder) { &::-moz-placeholder { color: @color; } // Firefox &:-ms-input-placeholder { color: @color; } // Internet Explorer 10+ &::-webkit-input-placeholder { color: @color; } // Safari and Chrome }

Generate columns via CSS within a single element.


.content-columns(@width; @count; @gap) { -webkit-column-width: @width; -moz-column-width: @width; column-width: @width; -webkit-column-count: @count; -moz-column-count: @count; column-count: @count; -webkit-column-gap: @gap; -moz-column-gap: @gap; column-gap: @gap; }

Easily turn any two colors into a background gradient. Get more advanced and set a direction, use three colors, or use a radial gradient. With a single mixin you get all the prefixed syntaxes you’ll need.


#gradient > .vertical(#333; #000); #gradient > .horizontal(#333; #000); #gradient > .radial(#333; #000);

You can also specify the angle of a standard two-color, linear gradient:


#gradient > .directional(#333; #000; 45deg);

If you need a barber-stripe style gradient, that’s easy, too. Just specify a single color and we’ll overlay a translucent white stripe.


#gradient > .striped(#333; 45deg);

Up the ante and use three colors instead. Set the first color, the second color, the second color’s color stop (a percentage value like 25%), and the third color with these mixins:


#gradient > .vertical-three-colors(#777; #333; 25%; #000); #gradient > .horizontal-three-colors(#777; #333; 25%; #000);

Heads up! Should you ever need to remove a gradient, be sure to remove any IE-specific

filter

you may have added. You can do that by using the

.reset-filter()

mixin alongside

background-image: none;

.

Utility mixins are mixins that combine otherwise unrelated CSS properties to achieve a specific goal or task.

Forget adding

class="clearfix"

to any element and instead add the

.clearfix()

mixin where appropriate. Uses the micro clearfix from Nicolas Gallagher.


// Mixin .clearfix() { &:before, &:after { content: " "; display: table; } &:after { clear: both; } } // Usage .container { .clearfix(); }

Quickly center any element within its parent. Requires

width

or

max-width

to be set.


// Mixin .center-block() { display: block; margin-left: auto; margin-right: auto; } // Usage .container { width: 940px; .center-block(); }

Specify the dimensions of an object more easily.


// Mixins .size(@width; @height) { width: @width; height: @height; } .square(@size) { .size(@size; @size); } // Usage .image { .size(400px; 300px); } .avatar { .square(48px); }

Easily configure the resize options for any textarea, or any other element. Defaults to normal browser behavior (

both

).


.resizable(@direction: both) { // Options: horizontal, vertical, both resize: @direction; // Safari fix overflow: auto; }

Easily truncate text with an ellipsis with a single mixin. Requires element to be

block

or

inline-block

level.


// Mixin .text-overflow() { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } // Usage .branch-name { display: inline-block; max-width: 200px; .text-overflow(); }

Specify two image paths and the @1x image dimensions, and Bootstrap will provide an @2x media query. If you have many images to serve, consider writing your retina image CSS manually in a single media query.


.img-retina(@file-1x; @file-2x; @width-1x; @height-1x) { background-image: url("@{file-1x}"); @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and ( min--moz-device-pixel-ratio: 2), only screen and ( -o-min-device-pixel-ratio: 2/1), only screen and ( min-device-pixel-ratio: 2), only screen and ( min-resolution: 192dpi), only screen and ( min-resolution: 2dppx) { background-image: url("@{file-2x}"); background-size: @width-1x @height-1x; } } // Usage .jumbotron { .img-retina("/img/bg-1x.png", "/img/bg-2x.png", 100px, 100px); }

While Bootstrap is built on Less, it also has an official Sass port. We maintain it in a separate GitHub repository and handle updates with a conversion script.

Since the Sass port has a separate repo and serves a slightly different audience, the contents of the project differ greatly from the main Bootstrap project. This ensures the Sass port is as compatible with as many Sass-based systems as possible.

Path Description
Ruby gem code (Sass configuration, Rails and Compass integrations)
Converter scripts (turning upstream Less to Sass)
Compilation tests
Compass package manifest
Sass, JavaScript, and font files
Internal tasks, such as rake and convert

Visit the Sass port’s GitHub repository to see these files in action.

For information on how to install and use Bootstrap for Sass, consult the GitHub repository readme. It’s the most up to date source and includes information for use with Rails, Compass, and standard Sass projects.

Bootstrap 4 | Grid System

Bootstrap Grid System allows up to 12 columns across the page. You can use each of them individually or merge them together for wider columns. All combinations of values summing up to 12 can be used.

Grid Classes: Bootstrap grid system contains five classes which are listed below:

  • .col- It is used for extra small screen devices (screen width less than 576px).
  • .col-sm- It is used for small screen devices (screen width greater than or equal to 576px).
  • .col-md- It is used for medium screen size devices (screen width greater than or equal to 768px).
  • .col-lg- It is used for large screen size devices (screen width greater than or equal to 992px).
  • .col-xl- It is used for xlarge screen size devices (screen width equal to or greater than 1200px).

Components of Grid System:

  • Containers: Bootstrap requires a containing element to wrap site contents in a grid system. The word container is used to contain the row elements and row elements containing the column elements.
  • Rows: Rows must be placed within the container or container-fluid for proper alignment and padding. Rows are used to create horizontal groups of columns.
  • Columns: Grid columns are created by specifying the number of twelve available columns you wish to span. For example, three equal columns would use three col-lg-4.

Example 1: This example uses bootstrap to create an equal width column grid on all devices and screen widths.

Output:

Example 2: This example uses bootstrap to create equal width responsive column grid. When the screen size is less than 576px the column automatically stack to each other.

Output:

  • Run-on large screen (Desktop, tablets):
  • Run-on small screen (mobile):

Example 3: This example uses bootstrap to create unequal width responsive column grid. When the screen size is less than 576px the column automatically stack to each other.

Output:

  • Run-on large screen (Desktop, tablets):
  • Run-on small screen (mobile):

Supported Browser:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!

Last Updated :
28 Apr, 2022

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

  • Bootstrap 4 Tutorial
  • Bootstrap 4 – Home
  • Bootstrap 4 – Overview
  • Bootstrap 4 – Environment Setup
  • Bootstrap 4 – Layout
  • Bootstrap 4 – Grid System
  • Bootstrap 4 – Content
  • Bootstrap 4 – Components
  • Bootstrap 4 – Utilities
  • Differences Between Bootstrap 3 and 4
  • Bootstrap 4 Useful Resources
  • Bootstrap 4 – Quick Guide
  • Bootstrap 4 – Useful Resources
  • Bootstrap 4 – Discussion

Bootstrap 4 – Grid System

Bootstrap heading

Bootstrap heading

Bootstrap heading
Bootstrap heading
Bootstrap heading

Create lighter, secondary text in any heading with a generic tag or the

.small

class.

h1. Bootstrap heading Secondary text
h2. Bootstrap heading Secondary text
h3. Bootstrap heading Secondary text
h4. Bootstrap heading Secondary text
h5. Bootstrap heading Secondary text
h6. Bootstrap heading Secondary text

Bootstrap heading Secondary text

Responsive CSS Grid Tutorial
Responsive CSS Grid Tutorial

Bootstrap 4 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.

Responsive classes

Bootstrap’s grid includes six tiers of predefined classes for building complex responsive layouts. Customize the size of your columns on extra small, small, medium, large, or extra large devices however you see fit.

All breakpoints

For grids that are the same from the smallest of devices to the largest, use the

.col

and

.col-*

classes. Specify a numbered class when you need a particularly sized column; otherwise, feel free to stick to

.col

.

col
col
col
col
col-8
col-4

Stacked to horizontal

Using a single set of

.col-sm-*

classes, you can create a basic grid system that starts out stacked and becomes horizontal at the small breakpoint (

sm

).

col-sm-8
col-sm-4
col-sm
col-sm
col-sm

Mix and match

Don’t want your columns to simply stack in some grid tiers? Use a combination of different classes for each tier as needed. See the example below for a better idea of how it all works.

.col-md-8
.col-6 .col-md-4

.col-6 .col-md-4
.col-6 .col-md-4
.col-6 .col-md-4

.col-6
.col-6

Row columns

Use the responsive

.row-cols-*

classes to quickly set the number of columns that best render your content and layout. Whereas normal

.col-*

classes apply to the individual columns (e.g.,

.col-md-4

), the row columns classes are set on the parent

.row

as a default for contained columns. With

.row-cols-auto

you can give the columns their natural width.

Use these row columns classes to quickly create basic grid layouts or to control your card layouts and override when needed at the column level.

Column
Column
Column
Column

Column
Column
Column
Column

Column
Column
Column
Column

Column
Column
Column
Column

Column
Column
Column
Column

Column
Column
Column
Column

Column
Column
Column
Column
Column
Column
Column
Column
Column
Column
Column
Column

You can also use the accompanying Sass mixin,

row-cols()

:


.element { // Three columns to start @include row-cols(3); // Five columns from medium breakpoint up @include media-breakpoint-up(md) { @include row-cols(5); } }

Senior Programmers vs Junior Developers #shorts
Senior Programmers vs Junior Developers #shorts

Grid Options

The following table summarizes how the Bootstrap 4 grid system works across different screen sizes:

Extra small (<576px) Small (>=576px) Medium (>=768px) Large (>=992px) Extra Large (>=1200px)
Class prefix
Grid behaviour Horizontal at all times Collapsed to start, horizontal above breakpoints Collapsed to start, horizontal above breakpoints Collapsed to start, horizontal above breakpoints Collapsed to start, horizontal above breakpoints
Container width None (auto) 540px 720px 960px 1140px
Suitable for Portrait phones Landscape phones Tablets Laptops Laptops and Desktops
# of columns 12 12 12 12 12
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) 30px (15px on each side of a column)
Nestable Yes Yes Yes Yes Yes
Offsets Yes Yes Yes Yes Yes
Column ordering Yes Yes Yes Yes Yes

Grid Classes

The Bootstrap 4 grid system has five classes:


  • .col-

    (extra small devices - screen width less than 576px)

  • .col-sm-

    (small devices - screen width equal to or greater than 576px)

  • .col-md-

    (medium devices - screen width equal to or greater than 768px)

  • .col-lg-

    (large devices - screen width equal to or greater than 992px)

  • .col-xl-

    (xlarge devices - screen width equal to or greater than 1200px)

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

sm

and

md

, you only need to specify

sm

.

CSS Grid trong 30 phút (2022)
CSS Grid trong 30 phút (2022)

Basic Structure of a Bootstrap 4 Grid

The following is a basic structure of a Bootstrap 4 grid:

First example: create a row (). Then, add the desired number of columns (tags with appropriate

.col-*-*

classes). The first star (*)
represents the responsiveness: sm, md, lg or xl, while the second star
represents a number, which should always add up to 12 for each row.

Second example: instead of adding a number to each

col

, let bootstrap handle
the layout, to create equal width columns: two

"col"

elements = 50% width to
each col. three cols = 33.33% width to each col. four cols = 25% width, etc. You
can also use

.col-sm|md|lg|xl

to make the columns responsive.

Grid Options

The following table summarizes how the Bootstrap grid system works across multiple devices:

Extra small

<768px

Small

>=768px

Medium

>=992px

Large

>=1200px

Class prefix
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
Bootstrap 4 Page sizes for UI designers grid system in xd(web designing full course in hindi)Part #4
Bootstrap 4 Page sizes for UI designers grid system in xd(web designing full course in hindi)Part #4

Customizing the grid

Using our built-in grid Sass variables and maps, it’s possible to completely customize the predefined grid classes. Change the number of tiers, the media query dimensions, and the container widths—then recompile.

Columns and gutters

The number of grid columns can be modified via Sass variables.

$grid-columns

is used to generate the widths (in percent) of each individual column while

$grid-gutter-width

sets the width for the column gutters.


$grid-columns: 12 !default; $grid-gutter-width: 1.5rem !default;

Grid tiers

Moving beyond the columns themselves, you may also customize the number of grid tiers. If you wanted just four grid tiers, you’d update the

$grid-breakpoints

and

$container-max-widths

to something like this:


$grid-breakpoints: ( xs: 0, sm: 480px, md: 768px, lg: 1024px ); $container-max-widths: ( sm: 420px, md: 720px, lg: 960px );

When making any changes to the Sass variables or maps, you’ll need to save your changes and recompile. Doing so will output a brand new set of predefined grid classes for column widths, offsets, and ordering. Responsive visibility utilities will also be updated to use the custom breakpoints. Make sure to set grid values in

px

(not

rem

,

em

, or ).

Tất tần tật về Grid System trong Bootstrap

Bài đăng này đã không được cập nhật trong 2 năm

Như các bạn đã biết thì Bootstrap đang là một trong nhưng framework css phổ biến nhất hiện nay và một tính năng vô cùng mạnh mẽ của nó chính là Grid System (Hệ thống lưới) giúp chúng ta xây dựng layout một cách dễ dàng và thuận tiện nhất. Do vậy hôm nay chúng ta cùng tìm hiểu về nó nhé!

Trước khi vào phần chính chúng ta hay cùng tìm hiểu qua một số khái niệm cơ bản của bootstrap sau đây.

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
HTML CSS Responsive Grid System with SASS, No Bootstrap, Like Bootstrap
HTML CSS Responsive Grid System with SASS, No Bootstrap, Like Bootstrap

Grid System Rules

Some Bootstrap 4 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
  • The biggest difference between Bootstrap 3 and Bootstrap 4 is that Bootstrap 4 now uses flexbox, instead of floats. One big advantage with flexbox is that grid columns without a specified width will automatically layout as "equal width columns" (and equal height). Example: Three elements with

    .col-sm

    will each automatically be 33.33% wide from the small breakpoint and up. Tip: If you want to learn more about Flexbox, you can read our CSS Flexbox Tutorial.

Note that Flexbox is not supported in IE9 and earlier versions.

If you require IE8-9 support, use Bootstrap 3. It is the most stable version of Bootstrap, and it is still supported by the team for critical bugfixes and documentation changes. However, no new features will be added to it.

Grid Options

The following table summarizes how the Bootstrap 4 grid system works across different screen sizes:

Extra small (<576px) Small (>=576px) Medium (>=768px) Large (>=992px) Extra Large (>=1200px)
Class prefix
Grid behaviour Horizontal at all times Collapsed to start, horizontal above breakpoints Collapsed to start, horizontal above breakpoints Collapsed to start, horizontal above breakpoints Collapsed to start, horizontal above breakpoints
Container width None (auto) 540px 720px 960px 1140px
Suitable for Portrait phones Landscape phones Tablets Laptops Laptops and Desktops
# of columns 12 12 12 12 12
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) 30px (15px on each side of a column)
Nestable Yes Yes Yes Yes Yes
Offsets Yes Yes Yes Yes Yes
Column ordering Yes Yes Yes Yes Yes
Learn Bootstrap in less than 20 minutes - Responsive Website Tutorial
Learn Bootstrap in less than 20 minutes - Responsive Website Tutorial

Responsive classes

Bootstrap’s grid includes five tiers of predefined classes for building complex responsive layouts. Customize the size of your columns on extra small, small, medium, large, or extra large devices however you see fit.

All breakpoints

For grids that are the same from the smallest of devices to the largest, use the

.col

and

.col-*

classes. Specify a numbered class when you need a particularly sized column; otherwise, feel free to stick to

.col

.

col
col
col
col
col-8
col-4

Stacked to horizontal

Using a single set of

.col-sm-*

classes, you can create a basic grid system that starts out stacked before becoming horizontal with at the small breakpoint (

sm

).

col-sm-8
col-sm-4
col-sm
col-sm
col-sm

Mix and match

Don’t want your columns to simply stack in some grid tiers? Use a combination of different classes for each tier as needed. See the example below for a better idea of how it all works.


.col-12 .col-md-8
.col-6 .col-md-4

.col-6 .col-md-4
.col-6 .col-md-4
.col-6 .col-md-4

.col-6
.col-6

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

xxl

. Add any number of unit-less classes for each breakpoint you need and every column will be the same width.

1 of 2
2 of 2
1 of 3
2 of 3
3 of 3

Setting one column width

Auto-layout for flexbox grid columns also means you can set the width of one column and have the sibling columns automatically resize around it. You may use predefined grid classes (as shown below), grid mixins, or inline widths. Note that the other columns will resize no matter the width of the center column.

1 of 3
2 of 3 (wider)
3 of 3
1 of 3
2 of 3 (wider)
3 of 3

Variable width content

Use

col-{breakpoint}-auto

classes to size columns based on the natural width of their content.

1 of 3
Variable width content
3 of 3
1 of 3
Variable width content
3 of 3

Bootstrap For Beginners | Grid system - 2024
Bootstrap For Beginners | Grid system - 2024

Alignment

Use flexbox alignment utilities to vertically and horizontally align columns.

Vertical alignment

One of three columns
One of three columns
One of three columns
One of three columns
One of three columns
One of three columns
One of three columns
One of three columns
One of three columns

One of three columns
One of three columns
One of three columns

Horizontal alignment

One of two columns
One of two columns
One of two columns
One of two columns
One of two columns
One of two columns
One of two columns
One of two columns
One of two columns
One of two columns

No gutters

The gutters between columns in our predefined grid classes can be removed with

.no-gutters

. This removes the negative

margin

s from

.row

and the horizontal

padding

from all immediate children columns.

Here’s the source code for creating these styles. Note that column overrides are scoped to only the first children columns and are targeted via attribute selector. While this generates a more specific selector, column padding can still be further customized with spacing utilities.

Need an edge-to-edge design? Drop the parent

.container

or

.container-fluid

.


.no-gutters { margin-right: 0; margin-left: 0; > .col, > [class*="col-"] { padding-right: 0; padding-left: 0; } }

In practice, here’s how it looks. Note you can continue to use this with all other predefined grid classes (including column widths, responsive tiers, reorders, and more).

.col-12 .col-sm-6 .col-md-8
.col-6 .col-md-4

Column wrapping

If more than 12 columns are placed within a single row, each group of extra columns will, as one unit, wrap onto a new line.

Since 9 + 4 = 13 > 12, this 4-column-wide div gets wrapped onto a new line as one contiguous unit.

Subsequent columns continue along the new line.

.col-9
.col-4Since 9 + 4 = 13 > 12, this 4-column-wide div gets wrapped onto a new line as one contiguous unit.
.col-6Subsequent columns continue along the new line.

Column breaks

Breaking columns to a new line in flexbox requires a small hack: add an element with

width: 100%

wherever you want to wrap your columns to a new line. Normally this is accomplished with multiple

.row

s, but not every implementation method can account for this.

.col-6 .col-sm-3
.col-6 .col-sm-3

.col-6 .col-sm-3
.col-6 .col-sm-3

You may also apply this break at specific breakpoints with our responsive display utilities.

.col-6 .col-sm-4
.col-6 .col-sm-4

.col-6 .col-sm-4
.col-6 .col-sm-4

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.

Learn how you can adjust column widths in Bootstrap with col-* and col-lg-* classes and combine them for different widths per device size

how can i make columns narrower in bootstrap?

what is bootstrap

What is bootstrap

what does d-none do?

how to display a card within a card using bootstrap

what is the purpose of bootstrap

what does `md` stand for in `col-md-4` for example

what does img-fluid do?

Does col-6 and col-sm-6 mean the same thing in Bootstrap?

what does "sm" in bootstrap grid mean?

how to make bootstrap navbar always be on top and displayed

In bootstrap, how to show an image only on mobile view?

What is bootstrap for?

I want to make a 1 row table with 6 columns in bootstrap, small size, able to have a small image and the date text above the image and the temperature text below the image

What is the difference between and

what is bootstrap?

Does anyone have a tutorial or explanation of boostratp to complement? It still has me a little confused

how can i align my navbar in bootstrap?

how do I align my navbar to the right in bootstrap?

Navbar with a logo to the far left and the links to the far right.

what is container-fluid

how to make three cards from boostrap to be in columns

how to add bootstrap form component styling

Make my cards in bootstrap horizontal

I want bootstrap cards containing an icon and a text

how can align my texts left in bootstrap divs?

why my row-cols do not work in bootstrap?

why my margins don't work in bootstrap?

bootstrap form grid with search bar and button example

how to adjust 3 images with different size into the same size using boostrap

how to import bootstrap

How to make a row with 7 equal columns in bootstrap

how to change font in bootstrap styled button

how to do 6 columns with bootstrap in vscode

how do i enable shadows in bootstrap?

what is col-sm-6

how to fix the posision of navbar in bootsdrap

what is class mt-5

Please add the code for 3 columns with 2 rows using boostrap

I do not understand why my code does not divide into columns even though I linked my code to bootstrap.

how do I centre text in a bootstrap column

I need a blog page with 3 cards where the most recent blog posts will go and a sidebar that includes recent posts and categories listed.

How do I turn a list into a layout of four columns with Bootstrap?

how to apply padding with bootstrap

what ist the form-control class doing in bootstrap?

What is the most important thing I need to know about bootstrap?

Can you please explain what is d-block, d-none, d-sm-none and all the combinations.

Use bootstrap to create 3 cards of the same width and height that are lined up in a row

How do I make the cards in my code the same height using bootstrap

how to create responsive link sizes with bootstrap

how do i hide an image only on mobile devices using bootstrap

Grid system

Use our powerful mobile-first flexbox grid to build layouts of all shapes and sizes thanks to a twelve column system, six default responsive tiers, Sass variables and mixins, and dozens of predefined classes.

Bootstrap 4 Grid System
Bootstrap 4 Grid System

Containers

Containers are the most basic layout element in Bootstrap and are required when using our default grid system. Choose from a responsive, fixed-width container (meaning its

max-width

changes at each breakpoint) or fluid-width (meaning it’s

100%

wide all the time).

While containers can be nested, most layouts do not require a nested container.

Use

.container-fluid

for a full width container, spanning the entire width of the viewport.

...

Bootstrap 4 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.

Bootstrap 4 Grid System Explained in Great Detail with Examples
Bootstrap 4 Grid System Explained in Great Detail with Examples

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.

1 of 2
2 of 2
1 of 3
2 of 3
3 of 3

Equal-width columns can be broken into multiple lines, but there was a Safari flexbox bug that prevented this from working without an explicit

flex-basis

or

border

. There are workarounds for older browser versions, but they shouldn’t be necessary if you’re up-to-date.

Column
Column
Column
Column

Setting one column width

Auto-layout for flexbox grid columns also means you can set the width of one column and have the sibling columns automatically resize around it. You may use predefined grid classes (as shown below), grid mixins, or inline widths. Note that the other columns will resize no matter the width of the center column.

1 of 3
2 of 3 (wider)
3 of 3
1 of 3
2 of 3 (wider)
3 of 3

Variable width content

Use

col-{breakpoint}-auto

classes to size columns based on the natural width of their content.

1 of 3
Variable width content
3 of 3
1 of 3
Variable width content
3 of 3

Equal-width multi-row

Create equal-width columns that span multiple rows by inserting a

.w-100

where you want the columns to break to a new line. Make the breaks responsive by mixing the

.w-100

with some responsive display utilities.

col
col
col
col

Grid System Rules

Some Bootstrap 4 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
  • The biggest difference between Bootstrap 3 and Bootstrap 4 is that Bootstrap 4 now uses flexbox, instead of floats. One big advantage with flexbox is that grid columns without a specified width will automatically layout as "equal width columns" (and equal height). Example: Three elements with

    .col-sm

    will each automatically be 33.33% wide from the small breakpoint and up. Tip: If you want to learn more about Flexbox, you can read our CSS Flexbox Tutorial.

Note that Flexbox is not supported in IE9 and earlier versions.

If you require IE8-9 support, use Bootstrap 3. It is the most stable version of Bootstrap, and it is still supported by the team for critical bugfixes and documentation changes. However, no new features will be added to it.

Bài 4: Hướng dẫn sử dụng Bootstrap grid
Bài 4: Hướng dẫn sử dụng Bootstrap grid

Nesting

To nest your content with the default grid, add a new

.row

and set of

.col-sm-*

columns within an existing

.col-sm-*

column. Nested rows should include a set of columns that add up to 12 or fewer (it is not required that you use all 12 available columns).

Level 1: .col-sm-3
Level 2: .col-8 .col-sm-6
Level 2: .col-4 .col-sm-6

Container

Container (vùng chứa) dùng để bao quanh nội dung, nội dung bên trong container sẽ có kích thước tùy thuộc vào màn hình hoặc mỗi điểm ngắt. Container có 3 loại class chính gồm:


container-fluid

Chiều rộng luôn là 100% kích thước thước màn hình.


container

Chiều rộng sẽ thay đổi tùy theo kích thước màn hình (theo bảng bên dưới).


container-{breakpoint}

Chiều rộng luôn là 100% đến khi nào đạt tới điểm ngắt của breakpoint.

New Grid System in Bootstrap 5 (Practical Examples)
New Grid System in Bootstrap 5 (Practical Examples)

Grid system

Hệ thống lưới của bootstrap sử dụng các container (vùng chứa), row (hàng) và col (cột) để xây dựng layout một cách linh hoạt, có thể bố trí và căn chỉnh nội dung theo từng kích thước màn hình khác nhau.

3.Cách nó hoạt động

  • Grid system sử dụng 6 breakpoint để có thể dễ dàng responsive. 6 breakpoint này được dựng trên min-width media queries trong css do vậy mỗi thuộc tính của breakpoint sẽ ảnh hưởng lên chính nó và các breakpoint ở trên.
    ví dụ: col-sm-4, phần tử chứa class này sẽ có độ rộng là 4 cột từ breakpoint sm trở lên.
  • Container sẽ chứa nội dung của bạn và căn chỉnh nó theo chiều rộng của màn hình thiết bị, nó cùng sẽ tự động thêm padding để tránh content bị sát lề khi chiều rộng màn hình quá nhỏ.
  • Row sẽ bao bọc các Column, class row sẽ có thuộc tính display: flex để khiến cho các cột nằm ngang. Mỗi cột sẽ có 1 phần padding ở 2 bên (được gọi là gutter) để điều chỉnh khoảng cách giữa các cột do vậy class row sẽ có thêm margin horizontal âm để xóa bỏ phần padding thừa ở 2 cột ngoài cùng 2 bên.
  • Các Column rất linh hoạt, mỗi hàng sẽ có đến 12 cột cho phép bạn có thể tạo ra các phần tử trên một hàng có số cột khác nhau, chiều rộng khác nhau.
    ví dụ: col-6, phần tử chứa class này sẽ chiếm chiều rộng bằng 1 nửa container chứa nó (50% width).
  • Gutters được sử dụng để điều chỉnh khoảng cách giữa các phần tử trên cùng 1 hàng.
    ví dụ: gx-* điều chỉnh khoảng cách ngang, gy-* điều chỉnh khoảng cách dọc và g-* điều chỉnh khoảng cách cả 2 chiều.
  • Chúng ta có thể sử dụng Bootstrap bằng source Sass để có thể dễ dàng tùy chỉnh grid system.

3.Breakpoint trên Grid system

Với mỗi breakpoint, container sẽ có chiều rộng khác nhau (như hình dưới) và chúng ta cũng có thể điều chỉnh độ rộng của mỗi cột bằng cú cú pháp

col-{breakpoint}-{number}

3.Chiều rộng Column tự động

Các Column có chiều rộng bằng nhau:

Chúng ta có thể sử dụng class

col

để khiến các cột có chiều rộng bằng nhau.

1 of 3
2 of 3
3 of 3

Chỉ định chiều rộng cho 1 Column riêng biệt

Bạn cũng có thể chỉ định chiều rộng cho một cột riêng biệt và các cột còn lại sẽ tự động điều chỉnh chiều rộng để lấp đầy dòng.

1 of 3
2 of 3 (wider)
3 of 3

Chiều rộng của Column theo content

Sử dụng cú pháp

col-{breakpoint}-auto

để có được một cột có chiều dài dựa trên nội dung bên trong của nó.

1 of 3
Variable width content
3 of 3

3.Responsive với Grid system

Áp dụng breakpoint

Chúng ta có thể sử dụng breakpoint để chỉ định độ rộng của cột cho từng màn hình cụ thể.

col-sm-8
col-sm-4

Đoạn code bên trên sẽ hiển thị 1 dòng với 2 cột từ màn hình sm trở lên, cột một có độ rộng là 8 ô còn cột 2 có độ rộng là 4 ô.

Kết hợp nhiều breakpoint

Nếu bạn muốn bố cục hiển thị khác trên một breakpoint nào đó thì hãy kết hợp chúng lại. Ví dụ nếu bạn muốn 1 bố cục hiển thị như sau:

Hiển thị trên màn hình md trở xuống:

Hiển thị trên màn hình md trở lên:

Thì hãy sử dụng đoạn dưới đây. Mỗi cột trong dòng sẽ chiếm 6 ô nhưng từ màn hình md trở lên mỗi cột sẽ chiếm 4 ô.

.col-6 .col-md-4
.col-6 .col-md-4
.col-6 .col-md-4

Tùy chỉnh số cột ở mỗi dòng

Chúng ta có thể sử dụng class

.row-cols-{number}

cho mỗi dòng để đặt nhanh độ rộng của các cột trong hàng thay vì phải set riêng cho từng cột riêng biệt (Lưu ý number chỉ nhận giá trị là 'auto' hoặc từ 1 đến 6 thôi nhé).

Column
Column
Column
Column
Column
Column
Column
Column

Ví dụ bên trên sẽ hiển thị 5 cột trên 1 dòng.

Lồng nhau

Trong mỗi cột có thể lồng thêm các dòng nữa nhé, như ví dụ bên dưới:

Level 1: .col-sm-3
Level 2: .col-8 .col-sm-6
Level 2: .col-4 .col-sm-6

Nesting

To nest your content with the default grid, add a new

.row

and set of

.col-sm-*

columns within an existing

.col-sm-*

column. Nested rows should include a set of columns that add up to 12 or fewer (it is not required that you use all 12 available columns).

Level 1: .col-sm-9

Level 2: .col-8 .col-sm-6
Level 2: .col-4 .col-sm-6

Bootstrap Grid System
Bootstrap Grid System

Example of Grid System

Following is an example of Bootstrap 4 grid system −

Example



<br /> Bootstrap 4 Example<br />
.grid_system div[class^="col"] { border: 1px solid white; background: #e4dcdc; text-align: center; padding-top: 5px; padding-bottom: 5px }

.col-sm-1
.col-sm-1
.col-sm-1
.col-sm-1
.col-sm-1
.col-sm-1
.col-sm-1
.col-sm-1
.col-sm-1
.col-sm-1
.col-sm-1
.col-sm-1
.col-sm-3
.col-sm-3
.col-sm-3
.col-sm-3
.col-sm-4
.col-sm-4
.col-sm-4
.col-sm-3
.col-sm-3
.col-sm-6
.col-sm-5
.col-sm-7
.col-sm-6
.col-sm-6
.col-sm-12



It will produce the following result −

Output

Breakpoint

Breakpoint (điểm ngắt) chính là thứ sẽ giúp bạn tùy chình layout trên mỗi viewport sizes (khung nhìn) khác nhau. Bootstrap bao gồm 6 breakpoint mặc định hay còn gọi là các grid tiers (tầng lưới), với mỗi breakpoint này chúng ta có thể áp dụng các class khác nhau của bootstrap để có thể tùy chỉnh layout theo ý muốn của mình. Chúng ta sẽ hiểu rõ hơn về nó qua những ví dụ sẽ đề cập sau.

Để ý thấy rằng từ màn hình xs trở lên mỗi breakpoint đều sử dụng dấu >= thay vì < điều đó cho thấy rằng những breakpoint này đang sử dụng thuộc tính min-width trong css. Thế nên các thuộc tính của breakpoint này sẽ áp dụng cho tất cả các kích thước màn hình lớn hơn hoặc bằng với width của breakpoint.

Bootstrap 4 Grid System | Bootstrap Grid Basic | Bootstrap Tutorial for Beginners
Bootstrap 4 Grid System | Bootstrap Grid Basic | Bootstrap Tutorial for Beginners

Two Unequal Responsive Columns

The following example shows how to get two various-width columns starting at tablets and scaling to large extra desktops:

Example

.col-sm-4

.col-sm-8

Tip: You will learn more about Bootstrap 4 grids later in this tutorial.

Bootstrap 4 Grid System

Customizing the grid

Using our built-in grid Sass variables and maps, it’s possible to completely customize the predefined grid classes. Change the number of tiers, the media query dimensions, and the container widths—then recompile.

Columns and gutters

The number of grid columns can be modified via Sass variables.

$grid-columns

is used to generate the widths (in percent) of each individual column while

$grid-gutter-width

allows breakpoint-specific widths that are divided evenly across

padding-left

and

padding-right

for the column gutters.


$grid-columns: 12 !default; $grid-gutter-width: 30px !default;

Grid tiers

Moving beyond the columns themselves, you may also customize the number of grid tiers. If you wanted just four grid tiers, you’d update the

$grid-breakpoints

and

$container-max-widths

to something like this:


$grid-breakpoints: ( xs: 0, sm: 480px, md: 768px, lg: 1024px ); $container-max-widths: ( sm: 420px, md: 720px, lg: 960px );

When making any changes to the Sass variables or maps, you’ll need to save your changes and recompile. Doing so will output a brand new set of predefined grid classes for column widths, offsets, and ordering. Responsive visibility utilities will also be updated to use the custom breakpoints. Make sure to set grid values in

px

(not

rem

,

em

, or ).

Bootstrap 4 Grid System

Bootstrap 4 Tutorial: Create Responsive Web Design With Bootstrap Grid System
Bootstrap 4 Tutorial: Create Responsive Web Design With Bootstrap Grid System

Z-index

Several Bootstrap components utilize

z-index

, the CSS property that helps control layout by providing a third axis to arrange content. We utilize a default z-index scale in Bootstrap that’s been designed to properly layer navigation, tooltips and popovers, modals, and more.

These higher values start at an arbitrary number, high and specific enough to ideally avoid conflicts. We need a standard set of these across our layered components—tooltips, popovers, navbars, dropdowns, modals—so we can be reasonably consistent in the behaviors. There’s no reason we couldn’t have used

100

+ or

500

+.

We don’t encourage customization of these individual values; should you change one, you likely need to change them all.


$zindex-dropdown: 1000 !default; $zindex-sticky: 1020 !default; $zindex-fixed: 1030 !default; $zindex-modal-backdrop: 1040 !default; $zindex-modal: 1050 !default; $zindex-popover: 1060 !default; $zindex-tooltip: 1070 !default;

To handle overlapping borders within components (e.g., buttons and inputs in input groups), we use low single digit

z-index

values of , , and for default, hover, and active states. On hover/focus/active, we bring a particular element to the forefront with a higher

z-index

value to show their border over the sibling elements.

by Elena-Cristina Conacel

Learn the Bootstrap 4 Grid System in 10 Minutes

The Bootstrap 4 Grid System is used for responsive layouts.

A responsive layout represents the way elements align in the page on different resolutions. It is important you understand how to use the grid before learning about any other Bootstrap 4 component, because whatever element you use, you will need to place it somewhere on the screen.

Let’s get started!

Table of Contents

The Bootstrap 4 grid consists of containers, rows and columns. We will take them one by one and explain them.

Bootstrap 4 Containers

A Bootstrap 4 container is an element with the class

.container

. The container is the root of the Bootstrap 4 grid system and it is used to control the width of the layout.

The Bootstrap 4 container contains all the elements in a page. This means your page should have the following structure: first the body of the HTML page, inside of it you should add the container and all the other elements inside the container.


...


The simple

.container

class sets the width of the layout depending on the width of the screen. It places the content in the middle of the page aligning it horizontally. There is equal space between the Bootstrap 4 container and the left and the right edge of the page.

The

.container

scales down in width as the screen width narrows and becomes full-width on mobile. The width of the container is defined inside the Bootstrap 4 library for every screen size. You can see the exact sizes here.

A full-width container takes 100% of the screen size regardless of the screen width. To use it you need to add the class .

container-fluid

.

Hello! I am in a simple container.
Hello! I am in a full-width container.

You can view the CodePen here.

To see the differences between the two types of containers, you can open the pen in your console and switch between screen sizes.

Bootstrap 4 Rows

Bootstrap 4 rows are horizontal slices of the screen. They are used only as wrappers for columns. To use them, you need the

.row

class.

...

Here are the most important things you need to remember about Bootstrap 4 rows:

  • They are only used for containing columns. If you place other elements inside the row along with columns you will not get the expected result.
  • They have to be placed in containers. If you don’t do this, you will get a horizontal scroll on your page. This happens because rows have negative left and right margins of 15. The container has 15px paddings so it counteracts the margins.
  • The columns have to be children of the row. Otherwise they will not align. The rows and columns are created to work together in this strict hierarchy.

Bootstrap 4 Columns

We can now get to the nice part of this tutorial, the Bootstrap 4 columns. Columns are great! They help you divide the screen horizontally.

If you place a single column in your row, it will take up all the width. If you add two columns, they will each take 1/2 from the width. And so it goes for any number of columns.

...
...
...
...
...
...
...
...

You can see the code live on CodePen.

Side note: Columns are not coloured. I just added colours for a more visually compelling description/so they look pretty.

Setting Sizes for Columns

Using the

.col

class sets the width for the column dynamically. That means that depending on the number of columns in a row, the width of a column will be the width of the container divided by the number of columns.

But there is another way to define columns. You can use classes for columns and define their size.

By default, the Bootstrap 4 grid consists of 12 columns. You can select any size from 1 to 12 for your column. If you want 3 equal columns, you can use

.col-4

for each one (because 3*4 cols each = 12). Or you can set different sizes for them. Here are some examples:

...
...
...
...
...
...
...
...

You can see the code live on CodePen.

If the sum of the cols in your row doesn’t get to 12, then they don’t fill the whole row. If the sum of the columns goes beyond 12 then it will move to the next line. The first line will only display the first elements that add up to 12 or lower.

Setting Breakpoints for Columns

If you take the example above and want to display it on mobile, you may run into some problems. Displaying five columns on mobile will make the content unreadable.

This is where one of the most powerful Bootstrap 4 components comes into play. In order to have different layouts on different screens you won’t need to write media queries, instead you can use the column breakpoints.

A breakpoint is a Bootstrap 4 variable that stands for a screen resolution. When you are specifying a breakpoint for a class, you are telling the class to be active only for resolutions that are at least as big as the number that the breakpoint holds.

The simplest class that we will learn about is the

.col-[breakpoint]

class. When you use this class, you are defining the behaviour for the columns only when they are displayed on devices that have a resolution of at least the defined breakpoint. Up to the given breakpoint, your columns will align vertically by default. And after your breakpoint, they will align horizontally because of the class.

Bootstrap has 4 breakpoints that you can use:


  • .col-sm

    for larger mobile phones (devices with resolutions ≥ 576px);

  • .col-md

    for tablets (≥768px);

  • .col-lg

    for laptops (≥992px);

  • .col-xl

    for desktops (≥1200px)

Let’s say you want to display two columns one after another vertically on small screens and on the same line on bigger screens. You will need to specify the breakpoint where the columns go on the same line.

In our example we will use the

.col-lg

breakpoint and see how the columns look on different screens. For resolutions that are lower than the given breakpoint (<992px) the columns will be displayed vertically. This means that on mobile devices and tablets, the columns will look like this:

And for devices that have a resolution that is higher or equal to the breakpoint (≥992px) the columns will go on the same row. This means that on laptops and desktops you will get this result:

...
...

You can see the code live on CodePen. If you open the Codepen in another window and see the page at different resolutions, you will see the columns change their positioning.

If you wanted for the 2 columns to go on the same line starting with larger mobile phones you would use

.col-sm

, for tablets

.col-md

and for extra large screens

.col-xl

.

Setting Sizes and Breakpoints for Columns

You can combine the sizes and breakpoints and use a single class with the format

.col-[breakpoint]-[size]

.

For example, if you want three columns of different sizes to align on a row starting with the laptop resolution you need to do this:

...
...
...

You will get this result on resolutions <992px:

And for screens that are ≥992px:

Again, you can see the code live on CodePen.

But what if you want to display one column per row on small mobile resolutions, two columns per row on tablets and four on laptops or devices with higher resolutions?

Then you add multiple classes for a single column to describe the behaviour for every resolution. Using multiple classes, you specify that the content will take six slots on tablets and three on laptops.

...
...
...
...

The result will show like this on tablets:

And like this on laptops and higher resolutions:

This example is also live on CodePen.

As an exercise, you can try and create rows with different number of columns depending on the screensize and verify the behaviour in your browser console.

Offsetting Columns

If you don’t want your columns to be next to each other, you can use the class

.offset-[breakpoint]-[size]

together with the

.col-[breakpoint]-[size]

.

Using this class is the same as adding an empty column before your column. Here is a simple example:

...
...

You can see the code live on CodePen.

You can use the class on any column in the row. Here are some more examples:

...
...
...
...
...

Nesting Columns

This may come as a surprise, but you can add a row inside a column!

The row in question (which will have the width of its parent column) will then be divided into 12 (smaller) columns that you can reference through the

.col-*

classes.

Let’s take a look at what happens when we insert a new row inside a column:

...

...
...
...

You can see the code live on CodePen.

Knowing this, you can go many levels deep to organise your information. The columns will provide a simple way for you to manage your space.

This wraps up the basic knowledge regarding the Bootstrap 4 responsive grid system. If you have questions, please let me know in the comments, I will be glad to answer.

Further Reading

If you have more time, here are some useful resources:

  • Official Grid Documentation from GetBootstrap
  • Video Tutorial from Scrimba

This article was initially posted on the BootstrapBay Blog. It is part of a larger series of Bootstrap 4 tutorials called 14 Days of Bootstrap 4. If you want to continue learning about the Bootstrap 4 components, these articles are a good place to start.

And if you want to jump start your development with a Bootstrap template, you can check out our marketplace.

But before delving deeper, take a moment to celebrate your newly acquired skills!?

CSS

Global CSS settings, fundamental HTML elements styled and enhanced with extensible classes, and an advanced grid system.

Global CSS settings, fundamental HTML elements styled and enhanced with extensible classes, and an advanced grid system.

Get the lowdown on the key pieces of Bootstrap's infrastructure, including our approach to better, faster, stronger web development.

Bootstrap makes use of certain HTML elements and CSS properties that require the use of the HTML5 doctype. Include it at the beginning of all your projects.



...

With Bootstrap 2, we added optional mobile friendly styles for key aspects of the framework. With Bootstrap 3, we've rewritten the project to be mobile friendly from the start. Instead of adding on optional mobile styles, they're baked right into the core. In fact, Bootstrap is mobile first. Mobile first styles can be found throughout the entire library instead of in separate files.

To ensure proper rendering and touch zooming, add the viewport meta tag to your .

You can disable zooming capabilities on mobile devices by adding

user-scalable=no

to the viewport meta tag. This disables zooming, meaning users are only able to scroll, and results in your site feeling a bit more like a native application. Overall, we don't recommend this on every site, so use caution!

Bootstrap sets basic global display, typography, and link styles. Specifically, we:


background-color: #fff;on the


body


@font-family-base,


@font-size-base, and


@line-height-baseattributes as our typographic base


@link-colorand apply link underlines only on


:hover

These styles can be found within

scaffolding.less

.

For improved cross-browser rendering, we use Normalize.css, a project by Nicolas Gallagher and Jonathan Neal.

Bootstrap requires a containing element to wrap site contents and house our grid system. You may choose one of two containers to use in your projects. Note that, due to

padding

and more, neither container is nestable.

Use

.container

for a responsive fixed width container.

...

Use

.container-fluid

for a full width container, spanning the entire width of your viewport.

...

Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases. It includes predefined classes for easy layout options, as well as powerful mixins for generating more semantic layouts.

Grid systems are used for creating page layouts through a series of rows and columns that house your content. Here's how the Bootstrap grid system works:


.container(fixed-width) or


.container-fluid(full-width) for proper alignment and padding.


.rowand


.col-xs-4are available for quickly making grid layouts. Less mixins can also be used for more semantic layouts.


padding. That padding is offset in rows for the first and last column via negative margin on


.rows.


.col-xs-4.


.col-md-*class to an element will not only affect its styling on medium devices but also on large devices if a


.col-lg-*class is not present.

Look to the examples for applying these principles to your code.

We use the following media queries in our Less files to create the key breakpoints in our grid system.


/* Extra small devices (phones, less than 768px) */ /* No media query since this is the default in Bootstrap */ /* Small devices (tablets, 768px and up) */ @media (min-width: @screen-sm-min) { ... } /* Medium devices (desktops, 992px and up) */ @media (min-width: @screen-md-min) { ... } /* Large devices (large desktops, 1200px and up) */ @media (min-width: @screen-lg-min) { ... }

We occasionally expand on these media queries to include a

max-width

to limit CSS to a narrower set of devices.


@media (max-width: @screen-xs-max) { ... } @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) { ... } @media (min-width: @screen-md-min) and (max-width: @screen-md-max) { ... } @media (min-width: @screen-lg-min) { ... }

See how aspects of the Bootstrap grid system work across multiple devices with a handy table.

Extra small devices Phones (<768px) Small devices Tablets (≥768px) Medium devices Desktops (≥992px) Large devices Desktops (≥1200px)
Grid behavior Horizontal at all times Collapsed to start, horizontal above breakpoints
Container width None (auto) 750px 970px 1170px
Class prefix
# of columns 12
Column width Auto ~62px ~81px ~97px
Gutter width 30px (15px on each side of a column)
Nestable Yes
Offsets Yes
Column ordering Yes

Using a single set of

.col-md-*

grid classes, you can create a basic grid system that starts out stacked on mobile devices and tablet devices (the extra small to small range) before becoming horizontal on desktop (medium) devices. Place grid columns in any

.row

.

.col-md-1
.col-md-1
.col-md-1
.col-md-1
.col-md-1
.col-md-1
.col-md-1
.col-md-1
.col-md-1
.col-md-1
.col-md-1
.col-md-1
.col-md-8
.col-md-4
.col-md-4
.col-md-4
.col-md-4
.col-md-6
.col-md-6

Turn any fixed-width grid layout into a full-width layout by changing your outermost

.container

to

.container-fluid

.

...

Don't want your columns to simply stack in smaller devices? Use the extra small and medium device grid classes by adding

.col-xs-*


.col-md-*

to your columns. See the example below for a better idea of how it all works.


.col-xs-12 .col-md-8
.col-xs-6 .col-md-4

.col-xs-6 .col-md-4
.col-xs-6 .col-md-4
.col-xs-6 .col-md-4

.col-xs-6
.col-xs-6

Build on the previous example by creating even more dynamic and powerful layouts with tablet

.col-sm-*

classes.

.col-xs-12 .col-sm-6 .col-md-8
.col-xs-6 .col-md-4
.col-xs-6 .col-sm-4
.col-xs-6 .col-sm-4

.col-xs-6 .col-sm-4

If more than 12 columns are placed within a single row, each group of extra columns will, as one unit, wrap onto a new line.

.col-xs-9
.col-xs-4Since 9 + 4 = 13 > 12, this 4-column-wide div gets wrapped onto a new line as one contiguous unit.
.col-xs-6Subsequent columns continue along the new line.

With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a

.clearfix

and our responsive utility classes.

.col-xs-6 .col-sm-3
.col-xs-6 .col-sm-3

.col-xs-6 .col-sm-3
.col-xs-6 .col-sm-3

In addition to column clearing at responsive breakpoints, you may need to reset offsets, pushes, or pulls. See this in action in the grid example.

.col-sm-5 .col-md-6
.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0
.col-sm-6 .col-md-5 .col-lg-6
.col-sm-6 .col-md-5 .col-md-offset-2 .col-lg-6 .col-lg-offset-0

Remove the gutters from a row and it's columns with the

.row-no-gutters

class.

.col-xs-12 .col-md-8
.col-xs-6 .col-md-4
.col-xs-6 .col-md-4
.col-xs-6 .col-md-4
.col-xs-6 .col-md-4
.col-xs-6
.col-xs-6

Move columns to the right using

.col-md-offset-*

classes. These classes increase the left margin of a column by columns. For example,

.col-md-offset-4

moves

.col-md-4

over four columns.

.col-md-4
.col-md-4 .col-md-offset-4
.col-md-3 .col-md-offset-3
.col-md-3 .col-md-offset-3
.col-md-6 .col-md-offset-3

You can also override offsets from lower grid tiers with

.col-*-offset-0

classes.

To nest your content with the default grid, add a new

.row

and set of

.col-sm-*

columns within an existing

.col-sm-*

column. Nested rows should include a set of columns that add up to 12 or fewer (it is not required that you use all 12 available columns).

Level 1: .col-sm-9

Level 2: .col-xs-8 .col-sm-6
Level 2: .col-xs-4 .col-sm-6

Easily change the order of our built-in grid columns with

.col-md-push-*

and

.col-md-pull-*

modifier classes.

.col-md-9 .col-md-push-3
.col-md-3 .col-md-pull-9

In addition to prebuilt grid classes for fast layouts, Bootstrap includes Less variables and mixins for quickly generating your own simple, semantic layouts.

Variables determine the number of columns, the gutter width, and the media query point at which to begin floating columns. We use these to generate the predefined grid classes documented above, as well as for the custom mixins listed below.


@grid-columns: 12; @grid-gutter-width: 30px; @grid-float-breakpoint: 768px;

Mixins are used in conjunction with the grid variables to generate semantic CSS for individual grid columns.


// Creates a wrapper for a series of columns .make-row(@gutter: @grid-gutter-width) { // Then clear the floated columns .clearfix(); @media (min-width: @screen-sm-min) { margin-left: (@gutter / -2); margin-right: (@gutter / -2); } // Negative margin nested rows out to align the content of columns .row { margin-left: (@gutter / -2); margin-right: (@gutter / -2); } } // Generate the extra small columns .make-xs-column(@columns; @gutter: @grid-gutter-width) { position: relative; // Prevent columns from collapsing when empty min-height: 1px; // Inner gutter via padding padding-left: (@gutter / 2); padding-right: (@gutter / 2); // Calculate width based on number of columns available @media (min-width: @grid-float-breakpoint) { float: left; width: percentage((@columns / @grid-columns)); } } // Generate the small columns .make-sm-column(@columns; @gutter: @grid-gutter-width) { position: relative; // Prevent columns from collapsing when empty min-height: 1px; // Inner gutter via padding padding-left: (@gutter / 2); padding-right: (@gutter / 2); // Calculate width based on number of columns available @media (min-width: @screen-sm-min) { float: left; width: percentage((@columns / @grid-columns)); } } // Generate the small column offsets .make-sm-column-offset(@columns) { @media (min-width: @screen-sm-min) { margin-left: percentage((@columns / @grid-columns)); } } .make-sm-column-push(@columns) { @media (min-width: @screen-sm-min) { left: percentage((@columns / @grid-columns)); } } .make-sm-column-pull(@columns) { @media (min-width: @screen-sm-min) { right: percentage((@columns / @grid-columns)); } } // Generate the medium columns .make-md-column(@columns; @gutter: @grid-gutter-width) { position: relative; // Prevent columns from collapsing when empty min-height: 1px; // Inner gutter via padding padding-left: (@gutter / 2); padding-right: (@gutter / 2); // Calculate width based on number of columns available @media (min-width: @screen-md-min) { float: left; width: percentage((@columns / @grid-columns)); } } // Generate the medium column offsets .make-md-column-offset(@columns) { @media (min-width: @screen-md-min) { margin-left: percentage((@columns / @grid-columns)); } } .make-md-column-push(@columns) { @media (min-width: @screen-md-min) { left: percentage((@columns / @grid-columns)); } } .make-md-column-pull(@columns) { @media (min-width: @screen-md-min) { right: percentage((@columns / @grid-columns)); } } // Generate the large columns .make-lg-column(@columns; @gutter: @grid-gutter-width) { position: relative; // Prevent columns from collapsing when empty min-height: 1px; // Inner gutter via padding padding-left: (@gutter / 2); padding-right: (@gutter / 2); // Calculate width based on number of columns available @media (min-width: @screen-lg-min) { float: left; width: percentage((@columns / @grid-columns)); } } // Generate the large column offsets .make-lg-column-offset(@columns) { @media (min-width: @screen-lg-min) { margin-left: percentage((@columns / @grid-columns)); } } .make-lg-column-push(@columns) { @media (min-width: @screen-lg-min) { left: percentage((@columns / @grid-columns)); } } .make-lg-column-pull(@columns) { @media (min-width: @screen-lg-min) { right: percentage((@columns / @grid-columns)); } }

You can modify the variables to your own custom values, or just use the mixins with their default values. Here's an example of using the default settings to create a two-column layout with a gap between.


.wrapper { .make-row(); } .content-main { .make-lg-column(8); } .content-secondary { .make-lg-column(3); .make-lg-column-offset(1); }

...
...

All HTML headings, through , are available.

.h1

through

.h6

classes are also available, for when you want to match the font styling of a heading but still want your text to be displayed inline.

h1. Bootstrap heading
Semibold 36px
h2. Bootstrap heading
Semibold 30px
h3. Bootstrap heading
Semibold 24px
h4. Bootstrap heading
Semibold 18px
h5. Bootstrap heading
Semibold 14px
h6. Bootstrap heading
Semibold 12px

Bootstrap heading

Bootstrap 4 Grid System

Bootstrap's grid system is built with flexbox and allows up to 12 columns across the page.

If you do not want to use all 12 columns 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

The grid system is responsive, and the columns will re-arrange automatically depending on the screen size.

Make sure that the sum adds up to 12 or fewer (it is not required that you use all 12 available columns).

Bootstrap Grid System
Bootstrap Grid System

Keywords searched by users: grid system in bootstrap 4

Bootstrap Grid System Explanation: Understand Bootstrap Columns
Bootstrap Grid System Explanation: Understand Bootstrap Columns
Bootstrap 4 Grid System
Bootstrap 4 Grid System
Bootstrap 4 | Grid System - Geeksforgeeks
Bootstrap 4 | Grid System - Geeksforgeeks
Bootstrap Grid In Canvas — How To Canvas
Bootstrap Grid In Canvas — How To Canvas
Bootstrap 5 Grid System - Examples And Tutorial
Bootstrap 5 Grid System - Examples And Tutorial
How To Use Bootstrap Grid - Bootstrap 4 Grid Layout - Youtube
How To Use Bootstrap Grid - Bootstrap 4 Grid Layout - Youtube
What'S New In The Bootstrap 4 Grid - Tutorialzine
What'S New In The Bootstrap 4 Grid - Tutorialzine
Bootstrap Grid Images :: Photos, Videos, Logos, Illustrations And Branding  :: Behance
Bootstrap Grid Images :: Photos, Videos, Logos, Illustrations And Branding :: Behance
Working With Bootstrap 4 Grid System For Creating Responsive Layouts - Dzone
Working With Bootstrap 4 Grid System For Creating Responsive Layouts - Dzone
Bootstrap Grid - Javatpoint
Bootstrap Grid - Javatpoint
Bootstrap 3 Grid System
Bootstrap 3 Grid System
How To Use Bootstrap Grid System?
How To Use Bootstrap Grid System?
Bootstrap 5 Columns And Grid System | Explained
Bootstrap 5 Columns And Grid System | Explained
Bootstrap 4 Grid System
Bootstrap 4 Grid System
Bootstrap 5 Grid System Tutorial - Youtube
Bootstrap 5 Grid System Tutorial - Youtube

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *