The max-height property is not applied to a border-box div with padding

One technique we use is the percentage trick on paddings to maintain aspect ratio in a div as the user scales their window. Here's an example:

.div {
    background: red;
    width: 80%;
    margin: 0 auto 10px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    padding-bottom: 20%;
}

Now, we want to set a maximum height for this div. Since the height of the div is determined by the padding and we need the div to be border-boxed, everything seems fine up to this point. But when attempting to use a max-height on the div, it doesn't work as expected.

.div {
    max-height: 60px;
}

I've created a fiddle to demonstrate the issue: http://jsfiddle.net/UxuEB/3/.

I've tested this on Chrome, Firefox, and Internet Explorer. Can someone please help me understand what I'm doing wrong or why this isn't working as intended?

Answer №1

Although I am quite late in providing this answer, I found myself dealing with the same issue today and stumbled upon this question as the first result on Google. Below is the code that I used to solve it, which may be helpful for someone facing a similar challenge in the future.

To begin, include an additional inner div:

<div class="control control-max-height">
  <div class="control-max-height-inner">
    Max-height
  </div>
</div>

Adjust the padding of the inner div while hiding the overflow of the outer div like so:

.control {
    background: red;
    width: 80%;
    margin: 0 auto 10px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.control-max-height {
    max-height: 120px;
    overflow: hidden;
}

.control-max-height-inner {
    padding-bottom: 20%;
}

It should be noted that this method assumes you are comfortable with concealing part of the inner element when it overflows. In my scenario, this was not an issue as the inner element only contained an empty link to enable the entire section to be clicked, while the outer element featured a centered background image and a border.

For a visual representation, please refer to the fiddle: http://jsfiddle.net/UxuEB/7/

Answer №2

When using the max-height property, it affects the element's height but you might also want to apply it to both the height and padding-bottom.

Some may confuse this with the box-sizing property which includes the padding in the overall height of the element (I was one of them too). However, as demonstrated in the jsFiddle example, this is not the case.

For instance:

  • If the element's content has a height of 100px.
  • Setting the max-height to
    50px</code</li>
    <li>Then adding a <code>padding-bottom
    of 100px (more than the element's original height).
  • The total height of the element will be 150px, including the added padding.

Check out the JsFiddle example for a visual demonstration: here

Answer №3

Taking inspiration from Mike's solution in his post, you can accomplish the same effect using just one DOM element and a pseudo element, like so:

Here is the HTML:

<div class="new-div"></div>

And here is the CSS:

div.new-div {
  max-height: 200px;
}

div.new-div::before {
  content: '';
  display: block;
  padding-bottom: 60%;
}

Answer №4

The min-height CSS property is used to specify the minimum height of an element when its height is determined by padding alone, whereas max-height does not have this restriction.

Interestingly, in 2020, the min and max CSS units have become quite useful for achieving desired outcomes.

.classthatshoulddefineheight {
   padding-bottom: min(20%, 60px); 
}

Therefore, if 20% results in a height greater than 60px, the height will be capped at 60px (taking the minimum value between them).

Answer №5

One potential drawback of Mike's solution (as well as Brad's approach, although Brad's method can help reduce the number of container levels) is its reliance on overflow: hidden - a limitation that may not be suitable for certain use cases.

To address this issue, I have modified the example by introducing an additional layer and utilizing absolute positioning instead of overflow: hidden.

http://jsfiddle.net/8saj91dh/1/

The key is to insert another container within the inner box, set it to position:absolute, and apply max-height to this new container as well:

.inner-inner {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  max-height: 150px;
}

By adding some extra DOM elements, this revised approach should function effectively across various scenarios in most modern browsers.

Answer №6

To fix the issue, you can use the CSS property display: flow-root; on the main container element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to navigate back to the top of the page once a link has been clicked?

One issue I'm facing is that whenever I click on a link in NextJS, it directs me to the middle of the page: <Link href={`/products/${id}`} key={id}> <a> {/* other components */} </a> </Link> I believe the problem l ...

What sets apart the <img> and <Image> layout attributes in NextJS?

While working on custom checkboxes, I came across a unique situation - the only way the positioning of the checkboxes aligns properly is if the classes '.init' and '.hover' are assigned to images, and the class '.done' is disp ...

extract individual components from the google books api

It has been quite a while since I last dabbled in JavaScript, so I decided to embark on a project creating a "bookcase" to organize the books I have read and those I still want to read. One challenge I encountered was figuring out how to separate the eleme ...

Finding a jQuery DOM element without using a loop

Can the element in variable d be identified directly instead of looping through each function? Take a look at the DOM below: <!DOCTYPE html> <html lang="en"> <head> <title></title> <script src="../jquery-ui ...

Tips for customizing the appearance of date circles and text in Vue V-Calendar.io

On v-calendar.io, there is a demo showcasing the correct display where the date "2018-01-01" has a red background and dark text: However, my display does not match that. I have included Vue.js and v-calendar through CDN, and the page is formatted in HTML ...

Ways to Get Rid of Line Beneath the Table

Can anyone assist me in removing the underline at the bottom of my table? Here is the code I am using: <table> <tbody> <tr> <td><iframe src="//player.vimeo.com/video/99496559" width="220" height="150" frameborder="0" allowfull ...

stacking order of floated and positioned elements

After researching on MDN and reading through this insightful blog post, it is suggested that in the absence of a z-index, positioned elements are supposed to stack above float elements when they overlap. However, upon closer examination, the example prov ...

Learn how to smoothly scroll to the top of a div by clicking on a team name

CSS Code .hover-div { position:absolute; margin-top:-150px; visibility:hidden; transition:all 0.5s linear 0s; } .team_hover:hover + .hover-div { margin-top:0px; visibility:visible; } .hover-div:hover { margin-top:0px; visi ...

Tips for avoiding a large <ul> element from spilling over the body in a flexbox design

I struggled to articulate the problem I am facing, and I apologize if it's still unclear So, in my app, I have 3 cards, and the 2 side ones contain lists (<ul>) that can become quite lengthy. I want the scrollbar to appear on the <ul> its ...

Designing numerous vertical lists in HTML

I need help with displaying multiple lists vertically using HTML For example: +--------+---------------------------------------------+--+ | Global | Region Country Currency Account Type Entity | | +--------+---------------------------------------------+ ...

Javascript Calculator with Dual Input Fields

I have been given a task to create a calculator by tomorrow using Javascript. Unfortunately, I am currently taking a distance course and Javascript has just been introduced in this assignment. While I am familiar with HTML and CSS, Javascript is something ...

Materialize.css | managing spaces, indentation, and 'overriding' in a span element

I recently started using a new framework called Materialize CSS for my project and I'm still getting the hang of it. One issue I've encountered is that long texts in my sidebar are creating large spaces between line breaks and strange indents. D ...

Efficiently shrink column width in Material-UI's <TableRow/> using ReactJS and Material-UI

At the moment, I am utilizing ReactJS along with Material-UI. One issue I am encountering is that when using Material-UI's <Table>, the columns' width are automatically set based on content which results in all columns having equal width. H ...

What is the best way to calculate the number of squares required to completely fill a browser window in real-time?

I am creating a unique design with colorful squares to cover the entire browser window (for example, 20px by 20px repeated both horizontally and vertically). Each square corresponds to one of 100 different colors, which links to a relevant blog post about ...

Craft a search bar inspired by Google's iconic design using CSS styling

I need to recreate a custom input styled like the Google Material Theme design. This is the desired outcome: https://i.stack.imgur.com/QU5dp.png While I am aware that frameworks/libraries can achieve this, it is part of my assignment to create it from s ...

What is the method for configuring body attributes in CSS with AngularJS?

Setting the background image of a page using CSS: body { background: url(http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-backg ...

I'm curious about the specific purpose of /1 in font styling at 16px

Can anyone explain the purpose of /1 in the font: 16px/1 style declaration? I removed the /1 from the code and noticed increased spacing between lines. What is the specific role of /1 in this situation? body { font: 16px/1 'Open Sans', sans ...

Locate the checkbox label using CSS

Is there a way to replace the standard checkboxes with font-awesome icons without modifying the generated HTML or using jQuery? EDIT: The code includes JavaScript that prevents me from making changes. Also, note that the label text class can be -1 or -2 a ...

Elevate your Material UI Avatar with an added level of

Attempting to give a MUI Avatar component some elevation or shadow according to the documentation provided here. <Avatar alt="Cindy Baker" src="/static/images/avatar/3.jpg" /> Enclosing the Avatar within a paper or Card element increases the size o ...

Customize Cell Styling with Bootstrap Full Calendar CSS

I am attempting to implement a Bootstrap calendar feature where cells are colored green if the timestamp is greater than today's date. This can be achieved by: $checkTime > $today cell.css = green background I came across this code snippet on St ...