What are the CSS dimensions for fixed width points?

<div class="container">
  <div class="content">
   Banana
  </div>
</div>

Suppose the 'content' element should always occupy a width of either 0, 25, 50, 75 or 100%, depending on its content. If the word 'Banana' takes up 20% of the 'container' width, then 'content' should be sized at 25%. If the word 'Mango' occupies 40% of the 'container' width, 'content' should have a size of 50%. The actual contents and widths are unknown, but they must align with these predefined values.

Can this behavior be achieved using only CSS? If not, what would be the simplest approach to accomplish this?

Edit: I intend to place any number of 'content' divs within the 'container'. Each one should adhere to one of these specified percentage widths. Additionally, the exact quantity of content divs is undetermined.

Answer №1

It's unlikely that achieving this effect using only CSS is possible.

However, below is a JavaScript solution that can accomplish it; the comments accompanying the code explain its functionality:

let list = document.getElementsByClassName('content');
let containerWidth = document.getElementsByClassName('container')[0].offsetWidth;

Array.from(list).forEach(function(el) {
  // By default, divs are set to 100% width, rendering this ineffective. We must
  // alter the display style to collapse the element width to match its content boundary:
  el.style.display = "inline-block";
  // Determine the closest multiple of 25%, 50%, 75%, or 100% in which the content fits:
  let newWidth = Math.ceil(el.offsetWidth / containerWidth * 4) * 25;
  el.style.width = newWidth + "%"; 
  el.style.display = "block"; // Return to the original display setting. (Ideally, we would have stored the original style.display value for flexibility, but for now, let's overlook that)
});
.content {
  border: 1px solid;
}
<div class="container">
  <div class="content">
    Apple
  </div>
  <div class="content">
    Something longer than that
  </div>
  <div class="content">
    Something even longer than that, plus some more text
  </div>
  <div class="content">
    Something even longer than even longer than even longer than even longer than that plus some more text even on top of that
  </div>
</div>

The elements will be assigned percentage widths by this method, contributing to responsiveness when the window size changes. To update the percentages themselves, it would be necessary to rerun the above code preferably with a debounced window.resize event listener.

Answer №2

Consider utilizing the power of flex boxes in your CSS design. By implementing

.container {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
}

You can easily adjust the width dynamically. It appears that the specific requirement you have may not be very responsive or practical. Another option is to use width: auto for automatic sizing of the element.

Answer №3

Suppose we cannot find a solution using css.

In JavaScript,

var content = document.getElementById('content')
var container = document.getElementById('container')
var contentWidth = content.getBoundingClientRect().width
var containerWidth = container.getBoundingClientRect().width
var percent = contentWidth / containerWidth * 100
if (percent === 0) {
   content.style.width = '0%'
} else if (percent < 25) {
   content.style.width = '25%'
} else if (percent < 50) {
   content.style.width = '50%'
} else if (percent < 75) {
   content.style.width = '75%'
} else {
   content.style.width = '100%'
}

Answer №4

This unique feature of "snapping" cannot be achieved using only CSS, however it is attainable through JavaScript by calculating the element's offsetWidth and adjusting its size accordingly.

// Locate your "content" element (you may require a more precise selector)
const content = document.querySelector('.content');
// Determine the percentage of the container that the element occupies when unstylized
const proportion = content.offsetWidth / content.parentNode.offsetWidth;
// Modify the width based on this proportion
if (proportion < .25) content.style.width = '25%';
else if (proportion < .5) content.style.width = '50%';
else if (proportion < .75) content.style.width = '75%';
else content.style.width = '100%';

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

Switch up the Background using .css and jCarousel

I am attempting to create a dynamic gallery using jCarousel and Ajax. The thumbnails are being loaded from a '.txt' file. I am trying to achieve the following effect: When a thumbnail is clicked, the background of the body changes. This action sh ...

Methods for automating the clicking of a hyperlink within Bootstrap tabs programmatically

I am attempting to programmatically trigger a click event on a specific href link within Bootstrap tabs. For reference, here is the link to the codepen: linkToCodePen <ul class="nav nav-tabs" id="myNavTabs"> <li class="active">&l ...

Display extensive text content in HTML for mobile devices

As I work on developing a web app, specific requirements must be met: Pages that can dynamically load large amounts of text (around 30-100 printed pages) in HTML using $.ajax based on complex functions The complete text must be loaded upfront and cannot ...

Tips for merging identical media queries into a single query using SASS

Previously, I organized my media queries in LESS by combining them at a single place like this LESS: .media-mixin(@break) when (@break = 1200px) { .abc{ color: red; } } .media-mixin(@break) when (@break = 1200px) { .xyz{ color: yellow; ...

Presenting CSV data in a tabular format using Angular and TypeScript

I am facing an issue with uploading a CSV file. Even though the table adjusts to the size of the dataset, it appears as if the CSV file is empty. Could this be due to an error in my code or something specific about the CSV file itself? I'm still learn ...

The concept of transparency and the overlay effect: uncovering the formula

I am working on developing a unique system that involves utilizing various div elements and adjusting their opacity levels. Here are some specific examples I am dealing with: envision all the divs being black. - When two divs overlap, each with an opacity ...

Having difficulties in loading the CSS file for my real-time chat application built with Express and Socket.io

Hi everyone, I've been struggling with an issue for the past couple of days where I can't seem to load my CSS for my Express app. If anyone has a solution, I would greatly appreciate the help. Below is my server.js code: const express = requir ...

Column Reordering in DataTable Causes Data to be Mapped Incorrectly

I have created a JSBin where you can view the code. However, due to CORS policy restrictions, the ajax URL I used is not functioning properly. The output generated shows that the data is mapped incorrectly in the columns. Can someone please help me figure ...

Exploring the asp.net MVC framework with the integration of HTML5 date input

Currently, I am working on an ASP.NET MVC project using Visual Studio 2013. One of the issues I am encountering is related to a date input field. When I click on the field and focus on it, the automatic HTML5 datepicker does not appear. If I enter the da ...

Implementing a dynamic navigation bar that expands and collapses on mouse hover in a React application

I have a side navigation bar on my webpage that I obtained from a React Bootstrap website, so the class names are already pre-loaded. Instead of using a toggle hamburger icon to expand or collapse the navigation, I want to achieve this functionality based ...

Intelligent programming and innovative thinking to streamline template diversity

My goal is to create multiple child websites using a base HTML/CSS template. Each child website will have unique color schemes and image variations for elements like <h> tags and background colors. I am searching for ways to easily modify the base th ...

Is it secure to use a unique, static HTML/CSS website?

As a web developer, I am currently working on hosting a Wordpress-website for a client. However, my frontend development skills have improved significantly and now I feel inspired to create a simpler and more customizable version on my own. This website i ...

Struggling to implement a click event followed by DOM manipulation

Every time I start the game, 4 characters are randomly generated in my starting function, and then they are displayed in the Character Div. The next step is to click on one of the four characters (vader, stormtrooper, luke, or yoda). Once a character is cl ...

Tips for displaying lower quality images while initially downloading higher quality versions

I need to download and display a large image in an img tag. Since the image is not Progressive JPEG, it will render as it downloads. Is there a way to show a low-resolution version of the image while it fetches from the server using only CSS or an HTML p ...

I am unable to modify the suffix located beneath the price of the product

Although I am not well-versed in PHP, I managed to create a code to display parcel descriptions below the price of products. The issue I am facing is that my code is calculating too many decimal places and not displaying the default currency, which should ...

What is the best way to add the SO-style <kbd> effect to my presentation made with HTML?

I'm currently utilizing reveal.js to construct an HTML-based presentation. My goal is to incorporate keyboard symbols like the ones found on SO and Github using the <kbd>SPACE</kbd> syntax, resulting in this glyph: SPACE. Despite attempti ...

What method sits snugly between prepend() and append()?

Just a quick question I have. I am attempting to align an element with my target. Usually, we use prepend (before the target) and append (after the target). Is there something similar that allows us to position that element directly on top of what we are ...

Discover how to effortlessly unveil JSON data by clicking on data retrieved from an API

After successfully parsing data from a Tumblr API, I encountered an issue when introducing tags within the body description, which includes images and hyperlinks. The main task at hand is to create a list of blog titles where the corresponding blog descri ...

Steps to clear input after deselecting all checkboxes:

My issue revolves around 5 checkboxes that I have on my webpage. I want to update the value displayed in an input tag based on the checkbox selection. While everything is working well when a checkbox is checked, the problem arises when all checkboxes are u ...

In Vue, applying CSS styles to D3's SVG elements may not work as expected when using the scoped attribute

Here is the code snippet of my component: <template> <div id="something" class="card"> </div> </template> const height = 200; const width = 200; let graph = d3 .select('#something') .append('svg') ...