Bootstrap Container Fluid for xs, sm

Viewed 33455

I'd like my outer-most div container to be just "container" for md and lg, but container-fluid for xs and sm. Can I achieve this natively? Do I need some additonal CSS?

Thanks.

5 Answers

With Bootstrap 4
Plain css:

@media (max-width: 768px) {
  .container {
    width: 100%;
    max-width: none;
  }
}

If you use Sass:

@include media-breakpoint-down(md) {
  .container {
    width: 100%;
    max-width: none;
  }
}

Demo: https://codepen.io/albertojacini/pen/KXgNqB

As noted, this is solution for Bootstrap 4

The Issue

Currently we have a full-width edge-to-edge fluid container for xs viewport. Then we have fixed size containers for sm, md, lg etc.

As sm viewport is also considered as a small device sometimes we would want to have full-width edge-to-edge fluid container there too, the same as for xs.

The Solution

If you compile Bootstrap from SCSS by yourself then you can simply override the variable $container-max-widths by removing max-width for sm breakpoint. This is a neat and clean solution I would recommend.

Find in the Bootstrap source code (vendor) _variables.scss:

$container-max-widths: (
  sm: 540px, // <-- we are going to remove this line
  md: 720px,
  lg: 960px,
  xl: 1140px
) !default;

Copy into your custom file and override by removing sm definition row and removing !default keyword e.g. in _my-variables.scss file:

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

Learn more about Theming Bootstrap with your own SCSS variables.

If you do not compile Bootstrap by yourself then you definitively might want to. It's the whole new level of magic you'll find there.

Bootstrap 4(.4) has it natively:

.container, which sets a max-width at each responsive breakpoint

.container-fluid, which is width: 100% at all breakpoints

.container-{breakpoint}, which is width: 100% until the specified

so, in your case, you can set:

<div class="container-md">

to achieve container at 100% width for xs and sm (fluid), and partial width above it

References: https://getbootstrap.com/docs/4.4/layout/overview/

If using Angular you can use ngClass with a ternary and have a function return true if window is less that the pixel breakpoint for lg?

main.component.html:

<div [ngClass]="isFluid() ? 'container-fluid' : 'container'">
      --your content--
</div>

main.component.ts:

isFluid() {
    return $(window).width() < 960;
}
Related