šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

A few considerations about the CSS min-width, width, and max-width properties

In theory, things should be pretty staring forward with the min-width, width, and max-width properties:

  • min-width will tell that an element it cannot be narrower than a specific value
  • width will tell that the element will always have a fixed width
  • max-width will tell that the element will not be wider than a specific value.

However, what happens if we have some conflicting values like:

.my-element {
    min-width: 300px;
    width: 500px;
    max-width: 100px;
}

Well, the general rule is that the min-width property overrides both the width and max-width properties and prevents the value of the width from becoming smaller than a specified value.

Alongside max-width and min-width we also have max-height and min-height so all that it is said about the width properties is also available for the height props.

Using percentages for min-width and max-width

One tricky (and useful) use case is when we use percentages to express the values for the max and min-width.

Having the width:100% means that we use the parent's width to calculate the current width value whereas max-width:100% uses the original width to calculate the maximum size.

So, let's say we have a jpg image file with a real width of 100px that it is placed in a div with a width of 200px. If we will have img { width:100%; } then this means that that the jpg image will be stretched to 200px.

While having img { max-width:100%; } means that the img will to its natural maximum of 100px. Check out the below codepen:

See the Pen
min-max-taz
by JS Craft (@js-craft)
on CodePen.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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