Ways to make a div adjust to the width of its content

Hello, this is my first time posting a question here. I have found many helpful Java answers in this community before, so I thought I'd give it a try. I did some research beforehand, but please let me know if I have duplicated a question or done anything wrong.

My current project involves creating a thumbnails gallery and I have created a jsfiddle link to showcase my progress.

HTML

<body>
  <div id="main">
    <div id="wrapper">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>
  </div>
</body>

CSS

#main {
  background-color: rgba(255, 105, 180, 0.5);
  height: 100vh;
  padding: 10px;
}

#wrapper {
  background-color: blue;
  display: inline-block;
  padding: 5px;
}

.box {
  display: inline-block;
  background-color: red;
  width: 200px;
  height: 200px;
  margin: 5px;
}

In the main div, I am attempting to center the red boxes horizontally without using text-align: center;. I want them to align left-to-right with space between them while keeping the entire block centered. My approach was to use a wrapper div for this purpose. However, I encountered an issue where the blue wrapper extends beyond its content filling the main div. I came across a solution on StackOverflow that suggests using inline-block to address this issue, but I am struggling to implement it correctly. I believe this should be a relatively simple fix, so what am I overlooking?

If you prefer a TLDR version, I have provided some snapshots here.

Thank you in advance!

Answer №1

To address this issue through CSS, you would need to create numerous media queries with specific values. Instead, I suggest using JavaScript to perform the following steps:

1) Determine the available width

2) Calculate the maximum number of blocks that can fit in one row

3) Set the required width for the wrapper container

Answer №2

One of the reasons your content expands to fit 100% of the space available is because the boxes are set as 'inline-block', which means they are part of a line that will take up 100% width if it wraps. The browser treats this like text, following standard behavior.

To change this, you can:

  1. Specify the maximum width of the container.
  2. Specify the number of elements that can be on one line before wrapping.

In either case, some assumptions/limitations need to be hardcoded (without using scripts or complex media queries).

The simplest way is to specify the maximum width of the wrapper:

body{
  width:100%;
}

#main {
  background-color: rgba(255, 105, 180, 0.5);
  height: 100%;
  padding: 10px;
  width:100%;
}

#wrapper {
  background-color: blue;
  display: block;
  padding: 5px;
  max-width:640px;
  margin: 0 auto;
}

.box {
  display: inline-block;
  background-color: red;
  width: 200px;
  /* To make it shrink instead of wrap, use:
  width: calc((100% / 3) - 15px);*/
  height: 200px;
  margin: 5px;
}

JS Fiddle: https://jsfiddle.net/Chipmo/z30fLv0v/


To control the number of elements before wrapping, add <br> tags after each box and selectively activate them using nth-child selector. While there may be ways without extra tags, this technique demonstrates the basic concept.

JS Fiddle: https://jsfiddle.net/Chipmo/xsf6c7e5/


SO snippets below:

Max-width

body{
  width:100%;
}

#main {
  background-color: rgba(255, 105, 180, 0.5);
  height: 100%;
  padding: 10px;
  width:100%;
}

#wrapper {
  background-color: blue;
  display: block;
  padding: 5px;
  max-width:640px;
  margin: 0 auto;
}

.box {
  display: inline-block;
  background-color: red;
  width: 200px;
  /* If you want it to shrink rather than wrap you could say
  width: calc((100% / 3) - 15px);*/
  height: 200px;
  margin: 5px;
}
<body>
  <div id="main">
    <div id="wrapper">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>
  </div>
</body>

Number of elements

#main {
  background-color: rgba(255, 105, 180, 0.5);
  height: 100%;
  padding: 10px;
  text-align: center;
}
/*needs 2 ID's to gain higher precedence than the text-align center from above */

#main #wrapper {
  background-color: blue;
  display: inline-block;
  padding: 5px;
  text-align: left;
}
.box {
  display: inline-block;
  background-color: red;
  width: 200px;
  height: 200px;
  margin: 5px;
}
#wrapper br {
  display: none;
}

/*change to 8n for every fourth, 4n for every 2nd etc etc 
  You will probably want to use media queries with this */

#wrapper br:nth-child(4n) {
  display: block;
}
<body>
  <div id="main">
    <div id="wrapper">
      <div class="box"></div><br>
      <div class="box"></div><br>
      <div class="box"></div><br>
      <div class="box"></div><br>
      <div class="box"></div><br>
      <div class="box"></div><br>
      <div class="box"></div><br>
    </div>
  </div>
</body>

Answer №3

To achieve the desired layout, utilize flexbox with the following properties:

#wrapper {
  background-color: blue;
  height: auto;
  padding: 10px;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-content: space-between;
  flex-wrap: wrap;
}

In order to position the last red box correctly, two invisible boxes have been added at the bottom of the layout.

View Fiddle

Snippet Preview

html,
body {
  width: 100%;
  height: 100%;
}
#main {
  width: 100vw;
  max-width: 640px;
  height: auto;
  background-color: rgba(255, 105, 180, 0.5);
  padding: 10px;
}
#wrapper {
  background-color: blue;
  height: auto;
  padding: 10px;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-content: space-between;
  flex-wrap: wrap;
}
.box {
  display: block;
  background-color: red;
  margin: 2.5px auto 10px;
  width: 200px;
  height: 200px;
}
.space {
  background: none;
}
<body>
  <div id="main">
    <div id="wrapper">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="space box"></div>
      <div class="space box"></div>

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

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

Triggering a jQuery event when a CSS property is altered

My current approach involves utilizing the .animate method to shift a div 100px to the right in just 1 second. Essentially, this means moving by 1px every 10ms. I am now exploring whether there exists an event that could be triggered after each individual ...

Adjust the size of an image to fit within a set height row using CSS grid

I have a container with fixed width and height where I want to display an image and some text. My goal is to have the text appear first, followed by the image filling up the remaining space in the container. Check out the image below for reference: Exampl ...

Internet Explorer is failing to render SVG as content within a pseudo element such as :before or :after

Looking to tackle an issue that stems from the following discussion: Is there a way to use SVG as content in a pseudo element :before or :after. I'm attempting to add a svg triangle after a div using a pseudo-class. div{ background-color: black; w ...

Ensuring that the text in the Bootstrap navbar is responsive for all screen

Yesterday, I inquired about how to modify my navbar menu to switch from horizontal to vertically arranged depending on layout. However, I've noticed that the responsiveness is not consistent when adjusting the window size. Is there a way to ensure my ...

Place text directly below the images for proper alignment

In my current rails app, I am working on the contributors page. Each member's name should be displayed centered beneath their respective images. Any assistance with this would be greatly appreciated. Below is a snippet from my member.html.erb file ...

Incorporate an icon into an Angular Material input field

I want to enhance my input search bar by adding a search icon from Angular Material : <aside class="main-sidebar"> <section class="sidebar control-sidebar-dark" id="leftMenu"> <div> <md-tabs md-center-tabs id=" ...

What exactly do discrete animations entail?

In the MDN animation documentation, it mentions a type of animation known as "discrete". Can you explain what this term signifies? ...

Resetting the Countdown Clock: A Transformation Process

I have implemented a countdown timer script that I found online and made some adjustments to fit my website's needs. While the current setup effectively counts down to a specific date and time, I now require the timer to reset back to a 24-hour countd ...

"Pressing the 'back' button on your browser takes

Is there a way to navigate back to the main page by clicking on an image? After selecting First, Picture1 will be shown. How can I go back to the selection page for further choices? <a href="picture1.jpg"> <h3>First</h3></a> <a ...

Is it possible for a Bootstrap modal dialog to overlay another dialog window?

<button class="btn" onClick="$('#firstModal').modal('show');">Click Here</button> <!-- Modal --> <div id="firstModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden=" ...

What is the best way to eliminate the gap between header, content, and footer sections when in mobile view?

This issue seems to only occur in mobile mode, where the blueviolet line is coming from the background color. https://i.stack.imgur.com/VBhIp.png link to the image body { background-color: blueviolet; } header, main, footer { background-color: #ff ...

Unable to implement Bootstrap 5 Hamburger Animation - Looking for solutions

SOLVED I successfully resolved the issue :) The challenge was: $(function () { $('.navbar-toggler-button').on('click', function () { $('.animated-hamburger').toggleClass('open'); //Chrome expert mode ...

What's preventing the buttons from shifting positions?

Having some trouble with my Minesweeper Web Game setup. My buttons are stuck in place and won't budge. Can someone help me figure out what's wrong? Here's the code snippet I've been working on (FYI, using NetBeans 8.1 IDE) HTML: <! ...

Styling with react-jss based on intricate conditionals

After experimenting with react-jss for a few weeks, I am faced with the challenge of styling components efficiently. With numerous conditionals in these components, I am striving to avoid creating an excess of new components that essentially share the same ...

Parsing CSS with PHP

Having an issue with my CSS link for images and need some assistance: background-image:url(images/background.gif); I'm looking to adjust the directory by adding ../. The code I aim to modify is as follows: background-image:url(../images/background. ...

The issue of pseudo elements not functioning properly in Material-UI makeStyles with React.js has been a frustrating

The use of pseudo elements in Material-UI makeStyles is not functioning correctly. innerBox: { borderRadius: "10px", background: "#fff", boxShadow: "0px 1px 3px 0px rgba(0, 0, 0, 0.36)", maxHeight: "50px", "& ...

Ways to evenly distribute children in a row using CSS

https://i.stack.imgur.com/HmziN.png The image above showcases the desired effect I am aiming for. It is important to note that the width of the container div may vary. The child elements should have consistent spacing between each other as well as the le ...

Issue with Bootstrap carousel: image protrudes past boundaries of parent container

Struggling with setting up a bootstrap carousel on my page. I want the image to extend beyond the parent div, positioned at the bottom rather than the top. How can I achieve this without disrupting the default carousel behavior? Here's a sketch of how ...

Text "movement/vibration" in screen when adjusting dimensions in Firefox for Mac

I am currently involved in a project centered around showcasing a variety of fonts to users for them to experiment with, allowing them to adjust size and spacing using sliders. While the functionality works seamlessly on Chrome and Safari, a peculiar issu ...

Utilizing jQuery or Javascript to obtain the title of the current webpage, find a specific string within it, and then apply a class to the corresponding element

Let's imagine I start with this: <title>Banana</title> and also have some navigation set up like this: <ul id="navigation"> <li> <a href=#">Banana</a> </li> </ul> Upon loading the sit ...