Explain Codes LogoExplain Codes Logo

How can I do width = 100% - 100px in CSS?

html
responsive-design
calc
flexbox
Nikita BarsukovbyNikita Barsukov·Aug 13, 2024
TLDR

Set width to 100% less a specific margin using the calc() function in CSS:

.your-element { width: **`calc(100% - 100px)`**; }

This reduces the element's total width by 100px, ensuring it remains responsive and adapts to various screen sizes while maintaining the desired spacing.

Supporting all browsers

Modern browsers generally support the calc() function. If you need support for older browsers, a jQuery fallback can be used:

// Good ol' jQuery if (!('calc' in document.documentElement.style)) { $('.your-element').css('width', 'auto').css('width', function() { // Sneaky subtraction - Warranty void if removed! return $(this).parent().width() - 100; }); }

Adding responsive flair with viewport units

You can make your designs even more responsive with viewport units (vw and vh):

.your-element { width: calc(100vw - 100px); // 100% viewport width minus 100px }

Keep in mind that viewport units can cause unexpected results on mobile browsers with hiding address bars, as they alter the viewport height.

Preventing overflow like a pro

Prevent content overflow with smart usage of margins and clearing divs:

.your-element { margin-right: 100px; // Maintain 100px gap at all costs! } .clearfix { clear: both; // Clearing the air after the party! }

Syntax: Devil is in the details

Spaces matter in calc(). calc(100% -100px) will throw an error, but calc(100% - 100px) will work just fine.

Nested divs: Creating layout "Russian Dolls"

An alternative to calc() is nesting divs and applying margins:

.outer { width: 100%; // Outer div got all the width } .inner { margin-right: 100px; // Inner div got the financial advice from /r/wallstreetbets }

Syntax errors: The CSS police

Ensure to include a unit after numbers. calc(100% - 100) is wrong, but calc(100% - 100px) is correct. It's the little tweaks that make the difference.

Flexbox and Grid: The unsung heroes

In scenarios where calc() doesn't cut it, consider alternatives like Flexbox or Grid that offer complex layout options without the need for calculations.

Mix and match with calc()

To manipulate layout further, multiple units can be combined within calc():

.example { width: calc(100% - 2em - 5%); // I heard you like widths, so I put width in your width! }

Using mixed units, e.g., em and %, can offer even more precise and adaptive designs.

Considerations with nested divs

When nesting divs, consider the impact of padding and borders in parent elements:

.container { width: 100%; padding: 10px; // Some breathing room box-sizing: border-box; // Packing suitcase like a pro } .child { width: calc(100% - 100px); // The child has boundaries! }