Asperger Asperger - 7 months ago 12
HTML Question

Prevent line break of a right positioned div inside a fluid container

So I have a red bar inside a container which lies between two black boxes. The boxes are fixed in size while the red bar and the container are based on percentages.

My goal is to reduce the size of the container, as well as the red bar without the right black box breaking onto the next line. I was able to resolve the issue via custom mathematical calculations in JavaScript, but I want to keep functionality and design separate. I feel that there must be some way to solve this with CSS without hacks or extra div tags.

How can this be achieved?



.container {
width: 80%;
height: 40px;
background: grey;
}
.box {
height: 50%;
border: 15px solid black;
border-top: none;
border-bottom: none;
float: left;
}
.bar {
width: 80%;
height: 100%;
background: red;
float: left
}

<div class="container">
<div class="box"></div>
<div class="bar"></div>
<div class="box"></div>
</div>





JSFiddle

Answer

CSS3 has a new flex display style supported by the major browsers.

.container {
  display: webkit-flex;
  display: flex;
  height: 40px;
  background: grey;
}
.box {
  height: 50%;
  border: 15px solid black;
  border-top: none;
  border-bottom: none;
}
.bar {
  width: 100%;
  height: 100%;
  background: red;
}
<div class="container">
  <div class="box"></div>
  <div class="bar"></div>
  <div class="box"></div>
</div>

To set the box elements to a specific width use min-width rather than width