When I apply a percentage to the height of a div element, it shrinks down to a height

I have several lists with a flex layout. Each column contains 3 list items, and the flex-basis is set to one-third. Within each li element, there is a div for a background image and another div to display text, which should be positioned below the image.

However, I am facing an issue where the image does not appear. Even though I set the image height to 80%, the div's height appears as 0 when inspected in Chrome. It only works when I use pixel values instead of percentages.

My question is, how can I set the div height to a percentage and still have the image displayed?

JSFiddle

html, body {
    margin: 0;
    height: 100%;
}
div {
    align-items: center;
    justify-content: center;
    height: 100%;
    display: flex;
    overflow: auto;
    background-color:aqua;
}
ul {
    margin-top: auto;
    margin-bottom: auto;
    height: calc(70% + 0px);
    padding: 0;
    display: inline-flex;
    flex-wrap: wrap;
    flex-direction: column;
    width: 100%;
    align-content: flex-start;
}
li {
    flex-basis: calc(100% / 3 - 2px);
    /* Subtract the border */
    color: firebrick;
    border: 1px solid firebrick;
    background-color: greenYellow;
    margin: 0px;
    list-style-type: none;
    box-sizing: border-box;
    background-size: contain;
    width: 200px;
}
.image {
    background-image: url("http://i.imgur.com/nswXRR4.jpg");
    background-size: contain;
    background-position: 50%, 50%;
    background-repeat: no-repeat;
    margin: 5px;
    height: 90%;
}
<div>
    <ul>
        <li>
            <div class="image"></div>
            <div class="num">1</div>
        </li>
        <li>
            <div class="image"></div>
            <div class="num">2</div>
        </li>
        <li>
            <div class="image"></div>
            <div class="num">3</div>
        </li>
        <li>
            <div class="image"></div>
            <div class="num">4</div>
        </li>
    </ul>
</div>

Answer №1

Even though the li element's height is set using

flex-basis: calc(100% / 3 - 2px);
, browsers typically interpret percentages differently in relation to the specification, assuming the height property is defined.

In my own experience, I have found that min-height, max-height, and flex-basis do not function as intended for a parent element when dealing with percentage heights, with only the height property working effectively even though it is not explicitly specified in the spec. (Note: Firefox may be changing its interpretation.)

To address this issue:

Instead of:

flex-basis: calc(100% / 3 - 2px);

Use: height: calc(100%/3 - 2px);

HOWEVER...

Based on your description:

The li contains a background image within one div and text within another div. You want the text positioned below the image while the image dominates the space.

This does not necessarily need to be an issue with percentage heights. You can retain the flex-basis on the li, make the li a flex container and apply flex properties to the image and text accordingly.

Adjust the li as follows:

li {
    flex-basis: calc(100% / 3 - 2px);
    /* Account for border */
    color: firebrick;
    border: 1px solid firebrick;
    background-color: greenYellow;
    margin: 0px;
    list-style-type: none;
    box-sizing: border-box;
    background-size: contain;
    width: 200px;

    display: flex; /* new */
    flex-direction: column; /* new */
}

Then update the styles for the image and text:

.image {
    background-image: url("http://i.imgur.com/nswXRR4.jpg");
    background-size: contain;
    background-position: 50%, 50%;
    background-repeat: no-repeat;
    margin: 5px;
    /* Remove height: 90%; */
    flex: 10 1 auto; /* new */
}

.num {
    flex: 1 1 auto;
}

DEMO

NOTE: flex: 10 1 auto; translates to flex-grow: 10, flex-shrink: 1, flex-basis: auto. Essentially, the flex item can take up to 10 times more space than siblings with flex-grow: 1, decrease proportionally with siblings having flex-shrink: 1, and initially size based on content.

Answer №2

Your li element lacks a specified height property, causing your .image div to attempt to be 90% of an undefined value, which defaults to 0.

To achieve the desired layout, you can set your li as display:flex and allow your .image div to expand more than the .num div using the following method.

There are various ways to adjust the properties like flex: 10 1 0 or

flex: 1 0 0</code to obtain the exact outcome that you seek. However, the below code serves as a basic example:</p>

<p><div>
<div>
<pre class="snippet-code-css lang-css"><code>html, body {
    margin: 0;
    height: 100%;
}
div {
    align-items: center;
    justify-content: center;
    height: 100%;
    display: flex;
    overflow: auto;
    background-color: aqua;
}
ul {
    margin-top: auto;
    margin-bottom: auto;
    height: calc(70% + 0px);
    padding: 0;
    display: inline-flex;
    flex-wrap: wrap;
    flex-direction: column;
    width: 100%;
    align-content: flex-start;
}

li {
    flex-basis: calc(100% / 3 - 2px);
    color: firebrick;
    border: 1px solid firebrick;
    background-color: greenYellow;
    margin: 0px;
    list-style-type: none;
    box-sizing: border-box;
    background-size: contain;
    width: 200px;
    display: flex;
    flex-direction: column;
}

.image {
     flex: 10 1 0; 
 }

.num {
  flex: 1 0 0;
}

.image {
    background-image: url("http://i.imgur.com/nswXRR4.jpg");
    background-size: contain;
    background-position: 50%, 50%;
    background-repeat: no-repeat;
    margin: 5px;
    height: 90%;
}
<div>
    <ul>
        <li>
            <div class="image"></div>
            <div class="num">1</div>
        </li>
        <li>
            <div class="image"></div>
            <div class="num">2</div>
        </li>
        <li>
            <div class="image"></div>
            <div class="num">3</div>
        </li>
        <li>
            <div class="image"></div>
            <div class="num">4</div>
        </li>
    </ul>
</div>

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

Creating a dynamic button with Angular that appears when focused

I want to have a button appear when the user focuses on an input with the ng-model=query. I know there is an ng-focus directive, but how can I implement it? <input type="search" ng-model="query"> <!--this is the button I need to show once th ...

Using Javascript and CSS to Float DIV Elements

Recently, I've been working on a small algorithm that adds a special class to an element when the mouse reaches the halfway point or beyond on the X-axis of the browser. I also have a screenshot that demonstrates where this application will be utiliz ...

The one-click button is functional on larger screens, while on mobile devices, only a double click will register

I am facing an issue in angular where a button works perfectly fine with one click on larger screens, such as Macbook. However, on iPhone, it requires a double click to function properly (it works fine on Android too). The alert triggers with a single cl ...

The strange behavior of !important, display:none, and .height()

While working with a piece of JS code yesterday, I stumbled upon something peculiar. There was a div element that was initially hidden using display:none, and I was utilizing its height in some JavaScript calculations. Everything was functioning properly u ...

When I view the website on a tablet in landscape mode, the navigation bar vanishes

I just finished creating a responsive menu for a website. Here's how it works: when viewing the site on a regular browser with a width less than 768px, the navigation menu items are stacked and hidden. To reveal them, the user needs to click on a tog ...

"Position centrally on the inside, using flexbox to fill the entire

Seeking assistance with aligning the text in the center of the flexboxes so that the h4 and p elements in the large box are centered within their respective boxes, as well as ensuring the text in the two smaller boxes is also centered. Any help would be gr ...

I'm looking to customize my d3.js Bar Graph by changing the color of each bar individually and adding a Scale for them. How can I

I am currently working on constructing a graph that illustrates the data for the Amount of Resources utilized Per Project by creating a bar graph. I am aiming to customize the colors of the bars so that each one has its own unique color. Currently, the col ...

What is the process for implementing the Google Analytics tag on a Streamlit-built website?

I want to monitor my Streamlit UI in Google Analytics. To achieve this, Google Analytics requires the following code snippet to be inserted into the <head> section of the HTML file. <script async src="https://www.googletagmanager.com/gtag/js? ...

Update the CSS for InputLabel

I have a drop-down list that I want to customize. The issue is illustrated below: I'm looking to center the text "choose format" within the field and adjust the font size. return ( <FormControl sx={{ m: 1, minWidth: 150 }} size="sm ...

ng-init assign value to a new object

<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl2" ng-init="person = new Person('Al ...

Choose a single SVG file based on its unique ID

Looking for some guidance - I have a vector file with 40 svgs all combined into one image. Each vector is identified by an id inside the <g> tag. How can I select a specific svg from this single file without choosing the entire image in html? PS: E ...

The issue of JQuery UI Dialog remaining open even after triggering it through an Input focus event

I am facing an issue with JQuery and JQuery UI. I thought upgrading to the latest stable version would solve it, but unfortunately, that was not the case. I am currently using Chrome. When I initiate the dialog by clicking on a specific element, everythin ...

Is the HTML templating mechanism compatible with Angular?

Trying to implement HTML templating in my Angular application, my code looks like the following: <script type='text/html' id="sampleId">...</script> However, upon loading the HTML, I noticed that the script block was not present in ...

Tips for automatically closing one element when another is clicked

My goal is to create a menu that displays when I click on a link, and if another menu is already open, it should close before displaying the new one. Essentially, I want to achieve an accordion menu where only one menu is open at a time. However, despite m ...

Strange Behavior of HTML5 Audio Elements

I'm currently in the process of designing a shop website with a nostalgic Windows98 theme. On the product's page, I want to include a preview of audio. Here is the CSS code that I have used for the HTML5 audio element: audio::-webkit-media-contr ...

Using AngularJS to interact with neighboring DOM elements

Imagine a scenario where there is a div containing 5 img elements. When one of these img elements is hovered over, the goal is to change the class of all the elements on its left side. <div id="stars"> <img src="star.png" data-rating="1" ng- ...

What is the best way to position a rectangle on top of a div that has been rendered using

I recently started using a waveform display/play library known as wavesurfer. Within the code snippet below, I have integrated two wavesurfer objects that are displayed and positioned inside div elements of type "container". My goal is to position my own ...

Tips for adjusting the position of overflowing text on a website using CSS in real-time

I'm currently working on an Angular application and I'd like to customize the styling so that any text exceeding 128 characters is not displayed. Ideally, if the text exceeds 128 characters, it should move to the left; otherwise, it should remain ...

Change the font awesome class when the button is clicked

Here is the code I have in this jsfiddle. I am trying to change the font awesome icon on button click using javascript, but it doesn't seem to be working. I am new to javascript, so please pardon me if this is a silly question. HTML <button id="f ...

Ways to showcase numerous products within a single category label

views.py : def get_meals(request): template = loader.get_template('café/meals.html') meal_data = MealInfo.objects.all() category_data = MealsCategory.objects.all() context = { 'meals': meal_data, ' ...