Ryan Langton Ryan Langton - 3 months ago 11
CSS Question

HTML Div list with varying location (right or left or full)

I have a list of objects that display in rows within a div. When they are full width, they work fine. As soon as I try to have the inner objects take up the left or right half of the parent, they cause all kinds of problems. Below is how I want them to appear, and how they actually appear. How do I achieve this layout with html/css? I've tried floating elements (which tends to mess up the parent list) and inline-block with no luck.

Plnkr: http://plnkr.co/edit/bP0ZWFplDFc6755LNNb5?p=preview

HTML:

<div class="employee-container">
<div class="full-shift">
<p>Person 1 <span>(40)</span></p>
</div>
</div>
<div class="employee-container">
<div class="full-shift">
<p>Person 2 <span>(40)</span> <span class="fa fa-clock-o"></span></p>
</div>
</div>
<div class="employee-container">
<div class="first-half">
<p>Person 3 <span>(40)</span></p>
</div>
<div class="second-half"></div>
</div>
<div class="employee-container">
<div class="first-half"></div>
<div class="second-half">
<p>Person 4 <span>(44)</span></p>
</div>
</div>


CSS:

.employee-container {
margin-bottom: 6px;
margin-top: 6px;
}
.employee-container > div {
padding: 3px;
background-color: lightsteelblue;
}
.employee-container > div .full-shift {
width: 100%;
}
.employee-container > div .first-half {
width: 50%;
}
.employee-container > div .second-half {
width: 50%;
}


Desired output:

Div

Actual output:

enter image description here

Answer

HTML changes include removing the "second-half" div from Person(3) and the "first-half" div from Person(4).

<div class="employee-container">
  <div class="first-half">
    <p>Person 3 <span>(40)</span></p>
  </div>
</div>
<div class="employee-container">
  <div class="second-half">
    <p>Person 4 <span>(44)</span></p>
  </div>
</div>

Float "first-half" left, and "second-half" right (Your original thought of 50% width was correct)

.first-half {
  width: 50%;
  float: left;
}
.second-half {
  width: 50%;
  float: right;
}

Change box-sizing to border box for all elements (if you're curious about what this property does, Paul Irish has a great blog post on it)

html{
    box-sizing: border-box;
}

*, *:before, *:after{
    box-sizing: inherit;
}

Here's a fiddle