I tried searching and could not find an exact similar question, so posting it here.
So I have a few block divs inside a flex wrapper with row wrapping, and I want to have a border for the wrapper. The issue I’m running into is that the border will always span 100% of the viewport, instead of being reduced to fit only the items. How can I achieve this without using media queries or JS? I would prefer solutions with inline styles as that’s the most preferable in this scenario.
Code samples:
Basic code for my blocks:
<div id="w1" class=wrapper style="display: flex; flex-direction: row; flex-wrap: wrap; justify-content: center; gap: 3px; border: 3px solid #000"> <!-- wrapper OPEN -->
<div id="b1" class="block" style="width: 250px;"></div>
.
.
.
<div id="b9" class="block" style="width: 250px;"></div>
</div><!-- wrapper CLOSE -->
So basically, this border should be here:
I tried a solution to add another wrapper outside with display:table
but it only works when all blocks are on the same row; when blocks wrap to the next row; it again takes up the entire width.
<div id="w0" class=outer style="display:table; margin:auto; border: 3px solid #000;"><!-- border wrapper OPEN -->
<div id="w1" class=wrapper style="display: flex; flex-direction: row; flex-wrap: wrap; justify-content: center; gap: 3px;"><!-- flex wrapper OPEN -->
<div id="b1" class="block" style="width: 250px;"></div>
.
.
.
<div id="b9" class="block" style="width: 250px;"></div>
</div><!-- flex wrapper CLOSE -->
</div><!-- border wrapper CLOSE -->
Thank you.
2
Answers
Instead of
display:flex;
usedisplay: inline-flex
.SideNote:
Your div is a block level element.
Block-level elements may contain other block-level elements or inline elements.
Inline elements cannot contain block-level elements.
If you define
display: inline-flex;
, it turns your element intoinline-block
element and You will get the best of both world.EDIT
It is how
flexbox
is supposed to behave. Otherwise, you should usegrid
instead offlexbox
.Yes possible.
If you can use external css file or internal css
assuming you want to columns, you can do something like this
If you have to use inline css then on the last
div.block
element, you should define above css styles inline.Depending on your need, the solution is to easily add a
width
for the flex wrapper and add thegap
value to it. in your case, it should bewidth: 503px
since each child haswidth: 250px
.Add
margin: 0 auto
for centering the wrapper.