Skip to content

Instantly share code, notes, and snippets.

@Skateside
Last active August 25, 2021 11:07
Show Gist options
  • Save Skateside/fc5938f598a54ad6bd9074da607efe0c to your computer and use it in GitHub Desktop.
Save Skateside/fc5938f598a54ad6bd9074da607efe0c to your computer and use it in GitHub Desktop.
Making 100vw take up the whole width without a horizontal scrollbar or overflow:hidden
/* https://css-tricks.com/full-width-containers-limited-width-parents/#no-calc-needed */
/* "No calc() needed" now with added calc()! */
.breakout {
--main-bar: var(--scroll-bar, 0px);
--main-half-bar: calc(var(--main-bar) / 2);
width: 100vw;
width: calc(100vw - var(--main-bar));
position: relative;
left: 50%;
right: 50%;
margin-left: -50vw;
margin-left: calc(-50vw + var(--main-half-bar));
margin-right: -50vw;
margin-right: calc(-50vw + var(--main-half-bar));
}
/*! https://davidwalsh.name/detect-scrollbar-width */
(function () {
"use strict";
var doc = document;
var html = doc.documentElement;
var body = doc.body;
/**
* Gets the width of the scrollbar.
*
* @private
* @author David Walsh
* @see https://davidwalsh.name/detect-scrollbar-width
* @return {Number}
* Width of the scrollbar in pixels.
*/
function getScrollbarWidth() {
// Create the measurement node
var scrollDiv = doc.createElement("div");
var scrollbarWidth = 0;
scrollDiv.style.cssText = (
"height:100px;" +
"overflow:scroll;" +
"position:absolute;" +
"top:-9999px;" +
"width:100px;"
);
body.appendChild(scrollDiv);
// Get the scrollbar width
scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
// Delete the DIV
body.removeChild(scrollDiv);
return scrollbarWidth;
}
/**
* Sets a custom CSS property on the HTML element that contains the
* scrollbar width.
*
* @private
* @see getScrollbarWidth
*/
function setProperty() {
html.style.setProperty("--scroll-bar", getScrollbarWidth() + "px");
}
/**
* Debounces a function so it will not execute until it hasn't been called
* for at least the amount of milliseconds declared in the wait parameter.
*
* @private
* @author David Walsh.
* @see https://davidwalsh.name/javascript-debounce-function
* @param {Function} func
* Function to debounce.
* @param {Number} wait
* Amount of milliseconds to debounce the function by.
* @return {Function}
* Debounced function.
*/
function debounce(func, wait) {
var timeout;
return function () {
var context = this;
var args = arguments;
var later = function () {
timeout = undefined;
func.apply(context, args);
};
window.clearTimeout(timeout);
timeout = window.setTimeout(later, wait);
};
}
setProperty();
window.addEventListener("resize", debounce(setProperty, 100));
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment