john mangual john mangual - 1 month ago 6
CSS Question

stacking divs -- mix of vertical and horizontal layout

I would like to accomplish a mix of horizontal and vertical layouts.

<div>
<div>
<span>A</span>
<span>B</span>
<span>C</span>
</div>
<div>
<span>D</span>
</div>
</div>


#1 It should look like this

A B C
<- D ->


#2 Instead I have the two div elements next to one another

A B C <- D ->





The real example has some very bad CSS that I recommend you not look at. I wanted to set the top three items to the same width of 25px and to be arranged next to one another. And a picture beneath the two control buttons.

For some reason, the
div
elements are not stacking on top of one another and instead sitting next to each other all in one row. Please help!

<div>
<div>
<button style="width: 25px; float: left;">-</button>
<span style="width: 25px; float: left; text-align: center;">0</span>
<button style="width: 25px; float: left;">+</button>
</div>
<div>
<img src="starry-night.jpg" width="500">
</div>
</div>

Answer

HTML:

<div>
  <div>
    <span>A</span>
    <span>B</span>
    <span>C</span>
  </div>
  <div>
    <span>D</span>
  </div>
</div>

CSS:

div {
  width: 100%;
}

div > div {
  display: flex;           /* pertinent */
  width: 100%;
}

div > div > span {
  width: 33%;              /* pertinent */
  justify-content: center; /* pertinent */
  margin: 1px auto;        /* pertinent */

  background: #333;
  text-align:center;
  color:#efefef;
  font-family: sans-serif;
}

https://jsfiddle.net/16dqk7cL/1/

Comments