Dimensions - Setting Limits

Chapter 35 3 mins

Learning outcomes:

  1. What is setting limits
  2. min-width and min-height
  3. max-width and max-height

Introduction

There are many instances when we need to set some limits on the dimensions of an element. These instances are where the properties min-width, max-width, min-height and max-height come to the rescue.

Let's explore them a bit more closely.

Maximum limits

As the names might suggest max-width and max-height set the maximum limit on the corresponding dimensions of an element i.e it can't exceed the specified value.

Both properties essentially operate the same way as do width and height i.e they accept the same values and units.

How can we use them in practice, is illustrated below with a couple of instances.

Set the width of div to fill all of its container width less than or equal to 500px. In other words this simply means that the width of div shall not exceed 500px.

div {
    width: 100%; /* fill all of the parent's width */
    max-width: 500px; /* no width beyond this */
    background-color: orange;
}
Div
Try resizing your browser to see how the width of this element might change.

Similarly, instead of on width we can apply these constraints to height as well. Here the height shall not go beyond 100px.

div {
    max-height: 100px; /* no height beyond this */
    background-color: orange;
}
Div
When writing long pieces of text this can be a benenifitial technique to our end since we can constrain heights to some maximum values and ensure content is displayed in the right size/

And in this way we can set any sort of limits on the widths and heights of elements. Try to play with these properties on your own to get the distinction between some made up examples.

Minimum limits

The properties min-width and min-height set a minimum width and height value respectively on a given element. The element will have to have at least the given dimensions.

Following we give a div that is at least 100px wide.

div {
    min-width: 100px; /* no width less than this */
    width: 20%;
    background-color: orange;
}
Div
If the 20% width of the div (in line 3) is less than 100px, then 100px is the value applied. It is the minimum width that the div shall have.

Same thing for min-height:

div {
    min-height: 100px; /* no height less than this */
    background-color: orange;
}
A short amount of text in a big div.

And this is all that's it for setting limits in CSS dimensions.

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage