A blog by Aaron Godin

S#001 - Breaking Out of a Fixed-Width Container

While responsive CSS is ideal, often there are cases where you need an element to be positioned outside of its parent. How can you do this when the parent element has a fixed width?

In this example, we are constrained by the Bootstrap grid with a fixed-width container of 1008px. Using absolute positioning, viewport units, and a bit of magic from CSS calc() (okay, math isn’t exactly magic), we could create a full bleed class that lets an element appear as though it’s outside of its parent.

@fixed-width-container: 1008px;
@full-bleed-class: full-bleed;

.@{full-bleed-class} {
  width: 100vw;
  position: absolute;
  left: ~"calc(-1 * ((100vw - @{fixed-width-container}) / 2))";

  @media (max-width: (@fixed-width-container - 1px)) {
    left: 0;
  }
}

The important part of what’s going on here is the calc() function. The end goal of the function is to find the distance between the left side of the parent element (fixed-width-container) and the browser window.

There are two scenarios this accounts for: one, when the viewport is 1008px or larger, and two, when the viewport is smaller than 1008px. Taking a look at the function for the left property, you can see that if 100vw happens to be 700px, the value will be 154px, causing the element to be positioned to the right of its parent’s left side. We handle this using the media query for scenarios that would cause the function to return a positive number.

Seeing It in Action

Here’s an example of a div with that class (with some modifications to fit the media queries for this website). Hint—try resizing your browser!


Content