Dendrowen Dendrowen - 5 months ago 13
CSS Question

div with max-width not taking the max width

I have a page with a div centered within a "main" div. The main div is full width and the inner div has a max-width equal to the width of the "main" div. When filling it up with elements it only fills up about half the screen. What am i doing wrong?

EDIT:
I noticed that some people misunderstood the text above. My elements (with float: left) will move beneath each other after 4 of them. At that point the div is about 1000px wide. This means that the max-width isn't 100% but somehow 50%. I checked in the browser and CSS but there is no other selector overriding those values.

CSS: (in sass)

#main
z-index: 0
width: 100%
min-height: calc( 100% )
background: #FFFFFF
position: absolute
left: 0px
top: 0px
padding: 50px 0px
text-align: center
div.container
position: absolute
top: 50%
left: 50%
transform: translate(-50%, -50%)
display: block
max-height: 100%
margin: 0 auto
width: auto
max-width: 100%
overflow-y: auto
overflow-x: hidden
text-align: left

div.box
width: 220px
height: 200px
border: 1px solid #5774FF
padding: 19px
margin: 10px
float: left
box-shadow: 1px 1px 4px #CCC


HTML:

<div id="main">
<div class="container">
<div class="box">
<form action="/save" method="post">
<input type="text" placeholder="code" name="name"/>
<select name="education">
<option value="3">option 3</option>
</select>
<button type="submit">save</button>
</form>
</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="box">
</div>
</div>
</div>

Answer

You're centering the container using the following code:

position: absolute
top: 50%
left: 50%
transform: translate(-50%, -50%)

When you're giving an element a position: absolute and giving a left: 50%, it will automatically move itself and it's subsequent children (if the children doesn't have position: absolute) to 50% from the left.

If you want the container to take up the full width, you'll have to remove the following:

position: absolute
top: 50%
left: 50%
transform: translate(-50%, -50%)