Blackbam Blackbam - 6 months ago 56
CSS Question

CSS: How can I force a display: table-cell box to have a fixed width of 50%?

HTML:

<div id="frontpage_boxes">
<div id="frontpage_boxes_inner">
<div id="fp_box1" class="fp_box">...</div>
<div id="fp_box2" class="fp_box">...</div>
<div class="clear"></div>
</div>
</div>


CSS:

#frontpage_boxes {
margin-bottom:60px;
margin-top:1vw;
display:table;
table-layout:fixed;
}

#frontpage_boxes_inner {
display:table-row;
}

.fp_box {
display:table-cell;
width:50%;
box-sizing:border-box;
text-align:center;
overflow:hidden;
}


The problem is I need display table-cell for the boxes to have equal height. They also should have equal width. Everything works great as long as there is a lot of space. However if space gets smaller the first box just grows bigger than 50% which breaks the layout.

How can I force a box with display:table-cell to have a width of 50% ignoring possibly available space?

Answer

What you've done is correct, they're both using up 50% of their parent, you need the parent to be 100% of the page for them to both be 50% of the page.

EDIT: So I added width:100% to the parent so it would take up the entire page.

See example below.

#frontpage_boxes {
  margin-bottom: 60px;
  margin-top: 1vw;
  display: table;
  table-layout: fixed;
  width: 100%;
}

#frontpage_boxes_inner {
  display: table-row;
}

.fp_box {
  display: table-cell;
  width: 50%;
  box-sizing: border-box;
  text-align: center;
  overflow: hidden;
}
<div id="frontpage_boxes">
  <div id="frontpage_boxes_inner">
    <div id="fp_box1" class="fp_box">...</div>
    <div id="fp_box2" class="fp_box">...</div>
    <div class="clear"></div>
  </div>
</div>