Explain Codes LogoExplain Codes Logo

Div width 100% minus fixed amount of pixels

html
responsive-design
css-hacks
browser-compatibility
Alex KataevbyAlex Kataev·Oct 11, 2024
TLDR

You can easily achieve a div width of 100% minus a fixed value using CSS's calc() function. Here's the core concept for a 40px subtraction:

div { width: calc(100% - 40px); /* Quick maths */ }

Just replace 40px with your desired fixed width to get an immediate, browser-friendly solution.

Scaling variant elements with calc()

The calc() function is a real game-changer, making complex calculations a breeze where fixed units or percentages need a little finesse. In other words, you can perform quick maths to create responsive designs, catering to almost every display size while ensuring a fixed amount of space for sidebar, margins, or even that cool cat video you want to embed.

.container { width: calc(100% - 200px); /* 200px fo' that cool sidebar */ } .content { width: calc(100% - 50px); /* 50px fo' some breathing space */ }

Resize in style using Flexbox

Instead of the calc() method, you can use Flexbox to let your divs flex their muscles in a fixed space. Flexbox, with its triad of flex-grow, flex-shrink, and flex-basis, gives you granular control over how your elements resize and adjust.

.parent { display: flex; /* Time to flex */ } .child-fixed { width: 150px; /* Fixed width - Immobile as a rock! */ } .child-flexible { flex-grow: 1; /* Soak up the remaining space */ }

Maintaining browser compatibility

Saving the day with its efficiency, calc() does have one kryptonite: browser compatibility. Don't worry, caniuse.com got your back! Also, for those classic legacy browsers, vendor prefixes are your superhero capes!

div { width: -webkit-calc(100% - 40px); /* Old School Chrome/Safari */ width: -moz-calc(100% - 40px); /* Firefox's Grandpa */ width: calc(100% - 40px); /* New age standard */ }

Extra tips and tricks

Making padding work in your favor

The calc() function is cool, but there's another trick you can pull. You can adjust div's padding or margin:

div { width: 100%; padding-right: 40px; /* Who needs calc()? */ box-sizing: border-box; /* Padding doesn't get on the weighing scale */ }

Structuring elements

You gotta have that flow. Maintain the hierarchy of elements. This way, you get a clear blueprint of your document structure. Go Van Gogh on your canvas!

Using CSS hacks when inevitable

While it's tempting to use a CSS hack for quick wins, try making it your last resort. Remember, you're an artist who thrives on sustainable and standards-compliant code!