Jonathan Lawrence Jonathan Lawrence - 9 months ago 27
CSS Question

Horizontally center two DIVs and have the distance between them scale with the browser width

I am making a Star Wars fansite and I have this setup. I need to make "legends-title" and "canon-title" horizontally centered in the larger div and have the space between them resize with the browser. (essentially, it should act as if I had created a 2-column table and horizontally centered the columns and when the browser resizes, the gap between them should resize to stay directly in the center of the left/right half of the div).

DEMO

HTML:

<div id="starwars-header">
<div id="legends-title">LEGENDS</div>
<div id="canon-title">CANON</div>
</div>


CSS:

#starwars-header {
background: rgb(54, 75, 95); /* Fall-back for browsers that don't support rgba */
background: rgba(54,75, 95, .9);
border: 5px solid black; /*width-style-color*/
text-align: center;
}

#legends-title{
display: inline-block;
color: white;
background-color: green;
}

#canon-title {
display: inline-block;
color: white;
background-color: red;
}

Answer Source

Use flexbox - updated fiddle

#starwars-header {
  background: rgb(54, 75, 95); /* Fall-back for browsers that don't support rgba */
  background: rgba(54,75, 95, .9);
  border: 5px solid black; /*width-style-color*/
  text-align: center;
  display: flex;
  justify-content: space-around;
  }
#legends-title{
     display: inline-block;
     color: white;
     background-color: green;
}
#canon-title {
     display: inline-block;
     color: white;
     background-color: red;
     /*padding-left: 10%; This increases*/
}
<div id="starwars-header">
    <div id="legends-title">LEGENDS</div>
    <div id="canon-title">CANON</div>
</div>


A second option, flexbox combined with pseudo elements on #starwars-header - updated fiddle

#starwars-header {
  background: rgb(54, 75, 95); /* Fall-back for browsers that don't support rgba */
  background: rgba(54,75, 95, .9);
  border: 5px solid black; /*width-style-color*/
  text-align: center;
  display: flex;
  justify-content: space-around;
}
#starwars-header::before,
#starwars-header::after {
  content: '';
}
#legends-title{
     display: inline-block;
     color: white;
     background-color: green;
}
#canon-title {
     display: inline-block;
     color: white;
     background-color: red;
     /*padding-left: 10%; This increases*/
}
<div id="starwars-header">
    <div id="legends-title">LEGENDS</div>
    <div id="canon-title">CANON</div>
</div>