Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center inline-blocks with dynamic width in CSS

Tags:

css

dynamic

width

So.. I have a dynamic width page. Below, the wrapper div centers the divs inside of it. However, each div has a style of:

display:inline-block;
width:400px; /* static */

This makes the inside divs, side by side. But that means that there is some whitespace left over depending on the width of the browser and how many divs can go side by side without breaking to the next line.

To get an idea of what I am going for, open up your Google Chrome New Tab page and drag your browser window to make it smaller. You will see that when you go too far, some of the chrome apps bump to the next line BUT it still stays centered.

In my case, they bump to the next line and become not centered.

This is what my code looks like:

<div class="wrapper">
    <div class="iB"></div>
    <div class="iB"></div>
    <div class="iB"></div>
    <div class="iB"></div>
    <div class="iB"></div>
    <div class="iB"></div>
</div>

I want the inside divs to be side by side unless there is not enough room in which case the end one will bump to the next line down, ALL while staying centered in the parent div.

Thanks for any help.

like image 246
Jacob Avatar asked Feb 21 '23 12:02

Jacob


2 Answers

If I understood you correctly adding text-align: center to your .wrapper styles should give the desired effect. See this fiddle for an example. Resize the result panel to watch the reordering of the boxes.

Like Akaishen already mentioned inline-blocks flow like text. That's why you can control their alignment with text-align. However if you want very fine control over your layout you might run into problems using inline-blocks. Since they flow like text whitespace between them is not ignored for instance. And unfortunately you can't really determine the absolute width of a space across browsers and OSs. The gaps between blocks in my example are caused by this.

like image 177
raphinesse Avatar answered Feb 24 '23 03:02

raphinesse


As you are using the display: inline-block the <div> tags are essentially inline elements and can be styled as such. text-align: center would center each element. At this point, you need a container / wrapper to define the maximum and minimum widths.

There could be a better way to achieve what you are looking for, and this is not exactly like how the Chrome windows work, though it's a start: fiddle

like image 37
Akaishen Avatar answered Feb 24 '23 03:02

Akaishen