Home >Web Front-end >CSS Tutorial >How Can I Set an Element's Height or Width as a Percentage Minus a Fixed Pixel Value in CSS?

How Can I Set an Element's Height or Width as a Percentage Minus a Fixed Pixel Value in CSS?

Linda Hamilton
Linda HamiltonOriginal
2025-01-03 01:25:39877browse

How Can I Set an Element's Height or Width as a Percentage Minus a Fixed Pixel Value in CSS?

Setting Width/Height as Percentage Minus Pixels

One common challenge in CSS is specifying an element's height or width as a percentage of its container minus a fixed value. Consider the following scenario:

You have a container

with an unknown height and a header
within it. Below the header, you want an unordered list to take up the remaining space, with a known header height of 18px. How can you specify the list's height dynamically as "100% minus 18px"?

Solution

The solution lies in utilizing the calc() function:

height: calc(100% - 18px);

This expression calculates the height by subtracting the known fixed value (18px), allowing the list to expand to fill the remaining space in the container.

Browser Compatibility

While calc() is widely supported, some legacy browsers require vendor-specific versions:

/* Firefox */
height: -moz-calc(100% - 18px);
/* WebKit */
height: -webkit-calc(100% - 18px);
/* Opera */
height: -o-calc(100% - 18px);

For complete cross-browser compatibility, consider using all the versions together with the standard syntax at the end:

/* Firefox */
height: -moz-calc(100% - 18px);
/* WebKit */
height: -webkit-calc(100% - 18px);
/* Opera */
height: -o-calc(100% - 18px);
/* Standard */
height: calc(100% - 18px);

The above is the detailed content of How Can I Set an Element's Height or Width as a Percentage Minus a Fixed Pixel Value in CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn