What is the best method to calculate the dimensions of flex items without relying on percentages?

Imagine this as the structure of my HTML, with an unspecified number of div elements:

<body>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</body>

My goal is to utilize Flexbox for organizing the elements in groups of 3 per row.

https://i.sstatic.net/9oeCX.png

This CSS code successfully achieves the layout I desire:

html, body {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

div {
  width: 30%;
  height: 20%;
  border: solid;
}

However, defining size using percentages can sometimes be cumbersome. Is there an alternative way to write the CSS without using percentage values?

After removing width:100% from html and body, the layout appears distorted:

https://i.sstatic.net/tmsEe.png

html, body {
  /*width: 100%;*/
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

div {
  width: 30%;
  height: 20%;
  border: solid;
}
<html>
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>
</html>

Answer №1

Is there a way to write the CSS code in this scenario without using percentages?

Apart from using percentages, other options like em, rem, vw/vh can be utilized. However, personally, I find % to be advantageous as it allows for effective scaling of the site.

Sometimes defining sizes using percentages can be challenging. For instance, removing width: 100% from the html, body rule may result in an unattractive layout.

This behavior is expected because the body does not adhere to traditional block-level display in HTML5 when set as display: flex;. Here is further information on the topic: Is body element a block level or inline element.

To address this issue effectively, we can leverage the properties of flexbox by configuring the html element as the primary flex container, the body as its flex item and secondary flex container for the div elements.

In addition, to resolve height issues encountered with percentages, where all ancestors must have a defined height, viewport units vh can be used.

html {
  display: flex;
}

body {
  flex: 1;                        
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

div {
  width: 30%;
  height: 20vh;                    
  border: solid;
}
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>


I would suggest utilizing a div instead of the body as a container

.container {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.container div {
  width: 30%;
  height: 20vh;                 
  border: solid;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Answer №2

When setting the size of your flex items based on the full height and width of the body element, consider utilizing viewport units instead of percentage units:

body {
  display: flex;
  flex-wrap: wrap;
}

div {
  flex: 1 0 30vw;
  height: 20vh;
  border: solid;
}
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>

According to the specification:

5.1.2. Viewport-percentage lengths: the vw, vh, vmin, vmax units

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

  • vw unit - Equal to 1% of the width of the initial containing block.
  • vh unit - Equal to 1% of the height of the initial containing block.
  • vmin unit - Equal to the smaller of vw or vh.
  • vmax unit - Equal to the larger of vw or vh.

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

Having Trouble Positioning Button at Bottom of Browser with Absolute Positioning in HTML and CSS

I am encountering an issue with positioning an element (<button id="foo">FAQ</button>). The CSS code I have for the button is: #foo { position: absolute; bottom: 0px;/* I have also tried using different units */ left: 0px;/* same t ...

What is the process for integrating Socket io into an external JavaScript file that is connected to an HTML file?

Currently, I am utilizing node js, socket io, and express to develop a multiplayer web game. To begin, the server initiates and listens on port 2000. Upon visiting localhost:2000, the file lobby.html is transmitted using: //app.js const express = require ...

Identify and target a particular DIV based on the URL for customization

My webpage has a collection of frequently asked questions (FAQs) on a page called faq.html. Here is an example structure: <div id="faq1">...</div> <div id="faq2">...</div> I am looking to create a pulsating or highlighting effect ...

Hover over the horizontal dropdown menu

I have attempted to create a horizontal drop down menu using this tutorial and demo I envision the menu to look like this: I want the sub-menu to appear to the right of the parent menu, as shown in this example The next step involves the sub-menus. The ...

The parent div's height is not compatible with the CSS grid

I created a CSS grid layout featuring a header, side menu, and scrollable content. My goal is to test this layout in a container div where I've specified the width and height. The layout adjusts well according to the container's width, but seem ...

Reverse animation transition not activating in CSS

In an attempt to create a side navbar using HTML/CSS, I implemented hover animations where hovering over an icon would cause it to double in size and disperse the rest of the items in the navbar. While I successfully achieved this animation with JavaScript ...

Assistance needed in keeping an image with absolute positioning CSS fixed to the top left corner of the browser

Looking for some CSS help as a beginner here! I've been trying to position a transparent PNG image over a centered table, but it seems stuck in the upper left corner of the browser. Absolute positioning should give me freedom to move it around, right? ...

Utilizing Capture Groups in CSS File for Regex Search and Replace

When it comes to extracting critical styles from a CSS file wrapped in a @critical rule, I run into some issues: @critical { .foo { ... } @media bar { ... } } The command I'm using for extraction involves sed search ...

Troubleshooting a problem with CSS styling in a jQuery bounce effect

In my current project, I am experimenting with creating a unique 'hovering' link. When the user hovers over an image and then moves the mouse away, I want the link to 'jump' back instead of using jQuery animation. +-----------+ | I ...

What is the best way to achieve CSS rounded corners while keeping the border lines sharp?

Currently, I am utilizing the border-radius property to make the corners of a div rounded. In addition, there is a border line at the bottom of the div. Here is an example: <div style="border-radius: .5em; border-bottom: 1px solid black">Content< ...

Eliminate unnecessary HTML elements in Angular

I am currently using ngSwitchCase for 3 different cases, and I have noticed that I am duplicating the same code inside each case. Is there a way to eliminate this redundancy? The redundant code is located within the "app-device" component <div *ngS ...

Custom-designed scroll bars that perfectly match the size of the content window

Currently attempting to adjust the layout of my webpages in order to enable scrolling for dynamic content across various pages. I have made adjustments to the header, footer, and sidebar elements, but am facing issues with implementing proper overflow prop ...

I'm experiencing some unusual behavior with the Windows media app when using HTML and CSS

I have a Windows Media Player box on my page, but it overlaps every piece of HTML code. How can I get it to move to the back so that I can still use it? Another problem is that everyone who visits my page needs a plugin to load it, even though most people ...

Steps for setting a background image behind radio buttons

I am currently facing a challenge in adding a background image to a div that contains some radio buttons and updating it dynamically with Angular based on the current page. app.controller('thingCtrl', function ($scope, $rootScope, $routeParams ...

Loading images in advance using JavaScript

I have been searching through multiple forums and cannot seem to figure out the issue. The problem I am encountering is related to a website where there are three images with a hover effect. When the page first loads, there is a delay in loading the backgr ...

What is preventing my hidden field from being filled by a JavaScript function?

I've recently developed a JavaScript function that generates a specific string required for another form on the website I'm currently working on. Initially, I decided to store this generated value in a hidden field and then submit it within an HT ...

The ng-click functionality seems to be malfunctioning when used within the controller in conjunction with ng-bind

After coding, I noticed that my ng-click function is not working. When I inspected the element, I couldn't find ng-click displayed anywhere. Can someone please help me figure out what I'm doing wrong? var app = angular.module('myApp' ...

Can $refs cause issues with interpolation?

I'm currently learning Vue.js and the course instructor mentioned that modifying the DOM element using $refs should not affect interpolation. In fact, any changes made directly to the DOM will be overridden by interpolation if it exists. However, in m ...

Alter the color of Material UI Raised Button when it is hovered over

I am trying to change the background color of a raised button on hover in Material UI. I attempted the following, but it did not work. Is there a way to modify the background color in Material UI for a raised button? Example.JS <RaisedButton ...

"Troubleshooting Issue: JavaScript and jQuery onClick Event Not Functioning Properly

Whenever I try to click on the "php1" div, nothing happens. The location.reload() function is only a placeholder used for testing if the onClick event is functioning properly. <div class="php-task"> <h1>PHP</h1> ...