Minimum and maximum width in css

CSS Properties – Max-width, Min-width, Max-height, and Min-height Explained with Examples

Nelson Michael

Nelson Michael

CSS Properties – Max-width, Min-width, Max-height, and Min-height Explained with Examples

If you’re building a website, making it responsive is one of the most important things you’ll do.

It can be difficult to create websites that look good across a variety of screen sizes. You’ll have to handle rendering an element’s width or height, and specifying varied width sizes using media queries is not easy.

While relative units such as «percentage percent» can be useful in some contexts, they can also be disastrous in others.

But don’t worry – characteristics like max-width and min-width are here to help. These properties allow us to avoid using media queries to solve some responsive challenges.

By the end of this article, you’ll know what max-width, min-width, and max-height are and how to use them.

The Max-width Property

The max-width property lets you specify an element’s maximum width. This means that an element can increase in width until it reaches a specific absolute or relative unit, at which point it should fix its width to that unit.

Here’s what I’m talking about:

Imagine setting the width of an element to 80% of the viewport’s width. If the viewport has a width of 375px, our element will have a width of 300px, which isn’t too shabby.

But what if we had a wider viewport, say 1300px, in which case our element will be 1040px wide.

This is where the max-width property comes in handy. When you’re using relative units like a percentage, setting a max-width property on an element causes it to keep increasing in width until it reaches a point we designate.

Читайте также:  Php error messages format

Notice how our card’s size never exceeded 350px? That’s how max-width works. It allows our card to grow on smaller screens.

If the width is less than 350px, it takes 80% of whatever the current screen size is. But as soon as the width reaches 350px, it clamps down and doesn’t exceed that set width.

Here’s what the code looks like:

//The card can not get larger than 350px. .card

The Min-Width Property

In contrast to the max-width property, the min-width property specifies the minimum width. It indicates the minimal possible width for an element.

In some cases, you may want your element to have flexible width, so you give it a width in a relative unit such as a percentage. But as the screen shrinks, the element’s width shrinks as well.

This is where min-width comes in – you can set a minimum width so that the card knows not to shrink smaller than the specified width.

//Here the card element can not get smaller than 250px .card < margin:0 auto; padding:1.5em; width:80%; max-width:350px; //here we set the min-width property min-width : 250px; height:50%; background: #FFFFFF; box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3); border-radius:4px; overflow:hidden; >

The Max-Height Property

The max-height property operates similarly to the max-width property, but it affects the height instead of the width.

// it fixes the height of an element to a specified unit, effectively stopping it from increasing in height .card < margin:0 auto; padding:1.5em; width:80%; max-width:350px; height:70%; //here we set the max-height for the card. max-height: 400px; background: #FFFFFF; box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3); border-radius:4px; overflow:hidden; >

The Min-Height Property

In contrast to max-height, the min-height property provides a minimum height for an element.

This occurs when the viewport shrinks and the element’s height cannot be reduced beyond a defined height unit.

Conclusion

Responsiveness is an important factor to consider in web development. Keeping track of how things appear across multiple screen sizes may be challenging, but the max-width, min-width and max-height, and min-height properties help tackle these challenges.

Читайте также:  Php javascript on load

These properties let you adjust the size of elements without needing to use media queries.

Nelson Michael

Nelson Michael

Nelson Michael is a frontend web developer and technical writer from Nigeria.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

CSS-свойства max-width, min-width, max-height и min-height: разбираем на примерах

Подпишись на наш телеграм-канал TechRocks WEB-разработка?

Перевод статьи «CSS Properties – Max-width, Min-width, Max-height, and Min-height Explained with Examples».

При создании сайта одна из самых важных задач — сделать его отзывчивым. То есть сайт должен хорошо выглядеть на экранах разных размеров. Для этого вам нужно управлять шириной и высотой элементов. А делать это при помощи медиа-запросов может быть непростой задачей.

В некоторых ситуациях вас могут выручить относительные единицы измерения, такие как проценты, но не всегда. Порой их применение приводит к катастрофическим результатам.

Помогут вам CSS-свойства max-width, min-width, max-height и min-height. Они позволяют решать некоторые задачи изменения размеров элементов без использования медиа-запросов.

Свойство max-width

С помощью свойства max-width можно установить максимальную ширину элемента. Это означает, что элемент может наращивать ширину, пок ане достигнет установленного предела (предел может быть как в абсолютных, так и в относительных единицах). Достигнув указанного ограничения, ширина фиксируется.

Читайте также:  Python dictionary with default

Рассмотрим пример. Представьте, что мы устанавливаем ширину элемента в 80% от зоны просмотра. Если зона просмотра — 375px, наш элемент будет иметь ширину 300px. При такой ширине качество не потеряется.

Но если зона просмотра у нас существенно больше, скажем, 1300px, ширина элемента станет 1040px.

Вот здесь нам пригодится свойство max-width. При использовании относительных единиц (процентов) добавление свойства max-width позволит увеличивать ширину элемента при увеличении размера зоны просмотра только до указанного предела.

Обратите внимание: размер карточки ни при каких условиях не превышает 350px. Так работает свойство max-width. Благодаря ему можно обеспечить увеличение размера карточки на маленьких экранах.

Если ширина экрана меньше 350px, карточка займет 80% от имеющейся ширины. Но если достигнута планка в 350px, ширина перестает увеличиваться.

Свойство min-width

В противоположность свойству max-width, свойство min-width определяет минимальную ширину элемента.

В некоторых случаях вам может быть нужно, чтобы элемент имел гибкую ширину, поэтому вы задаете ее в относительных единицах, например, в процентах. Но при уменьшении размера экрана размер элемента тоже уменьшается, и порой слишком сильно.

Здесь вам поможет свойство min-width. С его помощью вы можете установить минимальный размер, до которого может уменьшиться элемент. Это важно, например, для кнопок.

Здесь элемент карточки не может стать меньше, чем 250px в ширину.

Свойство max-height

Свойство max-height работает аналогично свойству max-width, но регулирует не ширину, а высоту элемента.

Здесь высота элемента фиксируется при достижении определенной высоты.

Свойство min-height

В противоположность max-height, свойство min-height позволяет установить минимальную высоту элемента.

Действие свойства проявляется, когда размер зоны просмотра уменьшается, а высота элемента уменьшается только до указанного предела.

Заключение

Отзывчивость — важный фактор в веб-разработке. Отслеживать все варианты изменения размеров элементов в зависимости от размеров экранов может быть сложной задачей, но CSS-свойства max-width, min-width, max-height и min-height помогут вам ее решить. С их помощью можно установить граничные размеры элементов и обойтись без медиа-запросов.

Источник

Оцените статью