Using the Min and Max Functions in CSS3

Two of the new and incredibly tantalizing functions in CSS3 are min() and max(). They are yet another tool in our crawl toward responsive design, and harnessing their simple, but highly effective power is vital for every developer.

Although none of the major browsers support either function at the time of this writing, they’re expected to be implemented soon. Let’s take a look at the syntax of these functions and explore their potential applications.

What do min and max do?

min()
The min() function returns the smallest value in a given set.
max()
The max() function returns the largest value in a given set.

Syntax

Using min() and max() is easy. Simply supply one of the functions with a comma-separated list of values, and the function will return either the largest or smallest of the values you provided, as seen below.

<selector> {
  <property>: min(<value>, <value>);
}

Examples

One of the most frustrating parts of any development project is ensuring your elements look the across multiple platforms. One obvious application for these two functions is in ensuring your font sizes are always relatively the same, no matter who views it.

Maximum Font-Size

body {
  font-size: min(11px, 0.9em);
}

The example above will make sure our font-size is always either 11px, or 0.9em; whichever is smaller.

Minimum Sidebar Width

Our sites are already being viewed on all sorts of different devices – from plasma TVs displaying at 1920×1080, to smartphones at 320×480. Let’s pretend our site has a sidebar with vital information, and we want to make sure it gets seen.

aside {
  width: max(250px, 25%);
}

In this example, our sidebar will always encompass at least 250px or 25%, which ever is bigger.

Conclusion

As you can probably imagine, these functions could prove to be invaluable in our ultimate goal of a design that looks and behaves the same way, no matter a user’s device, operating system, screen size, and resolution.

Web developers are already finding interesting uses for CSS3’s new functions. A quick and fun project might be to use these two functions as part of a dynamic progress bar. What uses can you think of for the min and max functions?

About: Kurt Maine

Kurt Maine is a Full-Stack Web Developer and an early adopter of Node.js whose professional experience has spanned several languages and frameworks, namely Ruby on Rails, C#/VB.NET and the Symfony and Laravel PHP frameworks.


Leave a Reply

Your email address will not be published. Required fields are marked *