Is there a way I can adjust the width of a DIV to automatically adjust to its content?

Is there a way to make a div adjust its width based on the width of its children, even if the children are too wide and collapse? Here is my CSS code:

    .outer{
        width: 100%;
        background-color: green;
    }

    .inner{
        width: auto;
        display: inline-block;
        margin: 0 auto;
        background-color: red;
    }

    .row{
        float: left;
        width: 250px;
        background-color: blue;
        display: inline-block;
    }

And this is my HTML structure:

<div class="outer">
    <div class="inner">
        <div class="row">asd1</div>
        <div class="row">asd2</div>
        <div class="row">asd3</div>
        <div class="row">asd4</div>
    </div>
    <div class="clear"></div>
</div>

Here is the link to my jsfiddle for reference: http://jsfiddle.net/vullnetyy/pshao68g/

My objectives are as follows:

  1. The red div should match the width of the three blue divs in its first row.
  2. The red div should be centered within the green div.
  3. Avoid the use of JavaScript.
  4. Avoid setting static widths for the red or green divs so that they can be responsive and accommodate any number of blue divs provided.

Answer №1

To properly center an element, you must follow these steps:

display: block;
width : %/px;
margin-left: auto;
margin-right:auto;

If you want the three blue divs to be contained within the red div and each be one-third of the width of the red div, assign each blue div a width of 33.333%.

For an example, refer to this link: https://jsfiddle.net/vullnetyy/pshao68g/

Answer №2

There are two conflicting issues at play in this situation.

1) In order to utilize margin-left/right auto, you need to have a set width.

2) When floating elements to match child width, using margin auto becomes difficult. Although float left was not explicitly added to the inner element, display:inline-block includes float left and other rules by default.

In this scenario, a compromise is necessary to achieve the desired outcome. Simply setting .inner to be the same as the row (250px in this case), along with removing display:inline-block can solve the issue.

Try applying the following CSS to your inner element and observe the results:

.inner{
        width: 250px;
        margin: 0 auto;
        background-color: red;
    }

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

Displaying an element when hovering over another using CSS

Currently, I am experimenting with a small CSS action that involves displaying another element when an A element is hovered over. The code I have so far is quite simple: <a title="#" class="portfolio-reaction" href="#"> <img src="http://i.imgur.c ...

Tips for preventing PyCharm from automatically completing HTML and Django template tags

While working on Django templates in PyCharm, I noticed that it automatically closes the tags. This can be helpful when starting a new tag, but it becomes annoying when I want to place existing content within a different tag because I have to delete or mov ...

Adjusting the front size while utilizing the SideNav feature in Materialize

While creating a website using Symfony and Materialize, my client requested to have the menu displayed on the side. I followed the guidelines from and successfully implemented the side menu on the left. However, I am encountering two issues: The first ...

Using Jquery to locate a specific data element

I have the code snippet below: <div id="mainMenuInternalMyProfile" class="mainMenuInternalTab" data-pagename="myprofile"> <div class="mainMenuInternalTabClickable">&nbsp;</div> <h4 class="mainMenuInternalTitle">MY PROFILE ...

Discovering the values within a separate JSON object

I have a collection of json objects that include information about different languages and user details. Languages User Details The user details contain a field for languages, which can have multiple values. Below is a sample json: $scope.languages = ...

Clickable link that directs to a particular tab on a webpage (cbpFWTabs)

I have been utilizing tabs from the codrops Tab Styles Inspiration and I am looking for a way to open specific tabs using URLs. For instance, if I wanted to open tab3, I could link it as www.google.com/index#tab3. Below is the code I am currently using: ...

Passing Data From AJAX to PHP Server Endpoint

I have been exploring this forum without much success. The following is the HTML code that I am currently working with: <form method="post" id="postform"> <input type="text" name="message" id="message" placeholder='Say "Hello!"&apo ...

Extract content from an HTML element and transfer it to PHP

Alright, listen up. I've got a task at hand where I need to fetch some information from my database by calling a PHP page through a link (<a href='name.php'>). Let's just say the code is speaking louder than my words: <?php ...

Tips for dynamically adding an external SVG animation to your website:

When trying to insert an animated SVG using jQuery or plain JavaScript, they appear static in Chrome and Edge, but display correctly in Firefox: $(".loader").prepend("<svg><use xlink:href='/images/icons.svg#loading-ring'></use> ...

The fixed sidebar refuses to pause before reaching the footer

I am facing an issue while building my blog. I am trying to figure out how to make my sidebar widget sticky and stop scrolling before reaching the #footer section. My widget is overlapping my footer and it would be really helpful if someone could assist m ...

Modify Knockout applyBindings to interpret select choices as numeric values

Utilizing Knockout alongside html select / option (check out Fiddle): <select data-bind="value: Width"> <option>10</option> <option>100</option> </select> Upon invoking applyBindings, the options are interprete ...

Update the text with jQuery and AJAX

I've written a script using jQuery and AJAX to change my button text from "Approve" to "Approved." However, I'm facing an issue where clicking on one row changes the button text for all rows. Here's the code for my button: <td> & ...

Adjust the scroll position in HTML by using a fixed navbar with Bootstrap 4

I am currently working on a single-page website with multiple sections. Users can navigate to these sections either by scrolling or by clicking on the navbar links. The issue I am facing is that the Bootstrap 4 navbar is fixed to the top, causing the conte ...

Issues with CSS margins in IE causing bugs?

Currently dealing with a CSS issue that seems to be specific to Internet Explorer. I haven't encountered it in Firefox, Safari, or Opera during testing with IE 11. The problem: I've set the top margin of the website content/stage to around 2%, ...

Adjust column content to fit width, instead of setting width to 100%

To create columns for the ul, I used flex-direction: column and flex-wrap: wrap. When the elements within the ul are split into multiple columns, each column takes on the width of the widest content in that column. However, if there is only one column, it ...

The JQuery duplication process did not function as anticipated

This question builds on a previous one related to jQuery cloning and incrementing IDs. The issue is that when adding new elements, the IDs are not being generated in the correct sequence. For example, if the initial ID is expy-1, clicking "add more" should ...

Issue with text-nowrap not functioning as intended within Bootstrap 4.5 table cells

Is there a way to eliminate the space between two columns in my layout? I want to get rid of the highlighted space below. I attempted using text-nowrap, but it didn't achieve the desired result. <link href="https://stackpath.bootstrapcdn.co ...

Styling HTML Select Box Options

My goal is to display the user's name and email within an option of a select box: <option>Adda <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caabaeaeab8aafb2aba7baa6">[email protected]</a></option& ...

Tips for preventing a bootstrap card image from overflowing in the card-body

I'm currently working with bootstrap cards and I've been able to prevent the card image from overflowing outside of the card area. However, I'm facing an issue where the bottom of the image overflows into the card-body region. I'm not s ...

Locate a specific class inside a div and switch the CSS style to hide one element and reveal another

I have two divs, each containing a span. By default, the display of each span class is set to none. My goal is to toggle the display property of the span within the clicked div. If the span is already visible, I want to hide it; if it's hidden, I want ...