How can I do width = 100% - 100px in CSS?
Set width to 100% less a specific margin using the calc()
function in CSS:
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:
Adding responsive flair with viewport units
You can make your designs even more responsive with viewport units (vw
and vh
):
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:
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:
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()
:
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:
Was this article helpful?