Stop elements from overextending within their parent container

I am facing an issue with two divs that are wrapped inside a container div. The bottom div contains a dynamically filled table, which determines the overall width of all the divs.

On the top div, I want to display several small red blocks that need to take up the available horizontal space. However, they should wrap to a new line if they exceed the maximum allowed width.

My desired outcome is illustrated in the following image:

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

Despite various attempts to style the red blocks using CSS (such as using small floating divs or inline-blocks), they consistently exceed the allowed width. As a result, all the divs end up wider than the table:

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

Is there a way to make sure that these red blocks only utilize the permitted width and move to a new line when they reach the maximum space?

Thank you!

UPDATE: I have provided a working example demonstrating the issue with the red blocks (which have varying lengths). They currently sit next to each other, expanding beyond the allowed width. It is crucial that they shift to a new line once the table's width limit is reached. http://codepen.io/anon/pen/bqobGp?editors=1100#0

table td{
  border:thin solid gray;
  line-height:25px;
  padding:0 5px;
}
.div1, .div2 {
  margin-top:15px;
  padding:20px;
  background:white;
  box-shadow:2px 0 3px rgba(0,0,0,.12)
}
.container {
  display:inline-block;
  background:#f1f1f1;
  padding:30px; 
}
.badge {
  line-height:30px;
  background:red;
  min-width:150px;
  color:white;
  margin:5px 10px;
  text-align:center;
  font-family:sans-serif;
  border-radius:5px;
  display: inline-block;
}

Answer №1

In my experience, creating the desired behavior can be achieved by utilizing HTML tables with a small width set on the parent table element...

Therefore, for your specific code, we can implement display: table and apply a small width to the .container class, along with white-space: nowrap; for .div2 to prevent line breaks within the table, like so:

.container {
  display: table; 
  width: 50px; /* keeping it small */
  ...
}

.div2 {
  white-space: nowrap; 
}

Feel free to check out the updated code pen

Answer №2

/* adjust size of 2nd div to fit the table */
.div2 {width: fit-content;} 

/* adjust size of first div to minimum size
 * ensuring it doesn't shrink beyond the width set by its siblings
 */
.div1 {min-width: available; width: min-content;} 

an alternative method

.container {width: min-content;}

These recent width values are quite new and the specifications are still evolving, so various browsers may offer support for them using different names or prefixes may be necessary.

Answer №3

I'm uncertain about the terminology you use for the "red" blocks in your CSS file. A simple and concise way to approach this would be to calculate the width dynamically.

For instance:

.parent {
  width: 100%;
  padding: 0;
  margin: 0;
  background: green;
  float: left;
}
.red_block {
  width: calc(100% / 5 - 20px); /* This calculation takes the full 100% width of the parent, divides it into 5 "red blocks," and subtracts 20px for each */
  height: 40px;
  padding: 0;
  margin: 10px;
  background: red;
  float: left;
}

<div class="parent">
    <div class="red_block"></div>
    <div class="red_block"></div>
    <div class="red_block"></div>
    <div class="red_block"></div>
    <div class="red_block"></div>
    <!-- Additional blocks will wrap to a new line -->
    <div class="red_block"></div>
    <div class="red_block"></div>
    <div class="red_block"></div>
</div>

VIEW DEMO

Does this explanation address your query?

UPDATE:

By using dynamic width calculations for your "red blocks," you can adjust their appearance for mobile devices through media queries. Here's an example:

@media screen and (max-width: 48em) {
    .red_block {
      width: calc(100% / 3); /* You can customize the width as needed, such as 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

What is the process of linking this JavaScript code to an outer stylesheet and integrating it with the HTML document?

After encrypting an email address using Hiveware Enkoder, the result can be found below. obfuscated code I typically include it directly inside the div as is. However, I would like to streamline my code by placing it in an external file. While I know ho ...

Displaying data from a JSON object to a DOM table can be achieved by dynamically generating table columns based on the keys within

There is a JSON object that I'm working with: [ { "SysID": "4", "Defect Classification": "Wrong Image Color", "1": "3.0", "2": "", "3": " ...

Struggling to make HTML5 validation function properly

I'm struggling to make HTML5 validation work in conjunction with AngularJS. Instead of displaying the error message, the form is submitted even when a field is required. If anyone has any insights on how to successfully implement HTML5 validation wi ...

The focusable attribute in SVG is malfunctioning

I've utilized the focusable attribute to ensure SVG elements receive focus within an HTML document. My goal is to navigate through SVG elements in the SVG tag using the TAB key, as indicated in this resource (http://www.w3.org/TR/SVGTiny12/interact.h ...

Looking for a way to keep the mobile ad unit fixed at the bottom of the screen

I am currently working on incorporating a 320x50 mobile ad into the mobile version of my website. The goal is to have the ad fill the entire width of a mobile device. However, the issue I'm facing is that the ad appears small and does not stretch acro ...

Maintaining the active status of section 1 after the page is refreshed using Javascript and CSS

I have a total of 3 buttons and 3 hidden sections available, which can be seen in the image below: click here for image description Whenever one of the buttons is clicked, the respective section transitions from being hidden to becoming visible: click he ...

I'm attempting to showcase an HTML file by using res.sendFile within the Express framework

As part of my workflow implementation, I have set up a scenario where upon user login, the credentials are sent via Ajax to an Express route for verification. If the user exists, the route responds with a message "authorised" triggering a second Ajax call ...

Step by step guide to creating individual counter sections

I have set up a counter section where the numbers go from 0 to a specific value. However, currently all three counters start counting simultaneously. Is there a way for the first counter to count up first, then once it's done, move on to the second c ...

Place a button at the center of a table

I am having trouble centering a button that I built inside a table. The CSS doesn't seem to be correct and I can't figure out why. I would appreciate any help with this issue. Additionally, the button needs to be displayed in an email, in case th ...

Using jQuery to insert HTML content into a div element by replacing a specific string

I am faced with a situation where I have <div class="test">hello everyone</div> and the challenge is to replace each instance of "hello" within this div with <h1>helllo</h1> In my attempt, I used $(this).text().replace("hello" ...

What is the best method to transfer and incorporate essays and information onto my HTML page?

Here are some unique events and observances for the month of December: DECEMBER 1 World AIDS Day National Pie Day National Eat a Red Apple Day Bifocals at the Monitor Liberation Day Day With(out) Art Day Rosa Parks Day DECEMBER 2 International Day for th ...

What are the options for transferring information between HTMX and Flask using JSON or another format aside from HTML?

So I am currently working on an app using Flask and HTMX. While I understand that htmx requires data in HTML format to swap with a specific target element, I am wondering if there is a way to update the current page using different formats such as dictiona ...

Is there a way to display a delivery estimate underneath the product title on a WooCommerce website?

How can I display Estimated delivery days below the product title to inform my customers about their order's arrival date, similar to the example on the page included in the link? I would like it to show varying days depending on the shipping class. ...

Arranging multiple lines of text above several images using CSS

I'm encountering issues when trying to place multiple texts in front of multiple images. I've managed to achieve this using absolute and relative positioning, with one text above one image. However, the problem arises when I try to apply this to ...

What is the best way to include basic static files and HTML together in a NodeJS environment?

I am facing an issue trying to serve an HTML file with its CSS and JS files in NodeJS using express.static(), but unfortunately, it is not working as expected. I have followed the steps shown in several tutorials, but for some reason, the output is not co ...

Having Trouble Adding a CSS File to Your Django Project? Can't Seem to Get it

I am feeling exhausted trying to solve this problem and now I am in desperate need of help. I have been attempting to add a main.css file to my Django project so that I can handle the CSS myself. I have watched numerous tutorials, but most have crashed m ...

Is it possible for an SVG to derive its dimensions from the containing element?

I am currently in the process of transitioning a Vue/Vuetify application from using web fonts for Material Design Icons to utilizing SVG icons instead. With the web font, an example of a heading that includes an icon looks like this: <template> &l ...

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 ...

Incorporating CSS and JS files into a WordPress theme

To incorporate Css & Js files into my website pages, I plan to insert the following code into the functions.php file: function cssjsloading(){ wp_enqueue_style('bootstrap-rtl', get_template_directory_uri() . '/css/bootstrap-rtl.css&apo ...

Selenium Webdriver is retrieving background colors with unexpected alpha values

When I need to retrieve the background-color of a WebElement, I typically use the following code: string color = IWebElement.GetCssValue("background-color"); Selenium often returns something like this for the color value: color = "rgba(153, 255, 255, 1) ...