Stormie Stormie - 2 months ago 5
CSS Question

How can I alternate the float of my content?

I want to create a layout for an itemised list of content like below:

Layout drawing

Each item is a container that has an image and block of text.

I have attempted to use

nth-child
and set different css float values based on if it is an odd or even child, but you can't set child properties using the nth-child selector.

HTML:

<div class="flex-container">
<div class="media-container ">
<img src="img/image.png">
</div>
<div class="text-container">
<div class="titles">
<h2>Title #1</h2>
</div>
<p>lots of words</p>
</div>
</div>
<div class="flex-container">
<div class="media-container ">
<img src="img/image.png">
</div>
<div class="text-container">
<div class="titles">
<h2>Title #1</h2>
</div>
<p>lots of words</p>
</div>
</div>
<div class="flex-container">
<div class="media-container ">
<img src="img/image.png">
</div>
<div class="text-container">
<div class="titles">
<h2>Title #1</h2>
</div>
<p>lots of words</p>
</div>
</div>


CSS:

.flex-container {
width: auto;
margin: 10px auto;
padding: 0 15px;
display: inline-flex;
}
.flex-container:nth-child(odd) {
.media-container {
float: left;
}
.text-container {
float: right;
}
}

.flex-container:nth-child(even) {
.media-container {
float: right;
}
.text-container {
float: left;
}
}

.media-container {
position: relative;
display: inline-block;
}

.media-container img {
width: 100%;
height: auto;
}

.text-container {
width: 30%;
margin: 0 10px;
align-self: center;
position: relative;
display: inline-block;
}


What is the easiest/neatest solution for creating this layout using CSS?

Answer

Something like this:

Use the nth-child on your "row" flex-containers and alternate the flex-direction.

.flex-container {
  padding: 0 15px;
  display: flex;
  width: 80%;
  border: 1px solid grey;
  margin: 1em auto;
}
.flex-container:nth-child(odd) {
  flex-direction: row;
}
.flex-container:nth-child(even) {
  flex-direction: row-reverse;
}
.media-container img {
  width: 100%;
  height: auto;
}
.text-container {
  width: 30%;
  margin: 0 10px;
}
<div class="flex-container">
  <div class="media-container ">
    <img src="http://www.fillmurray.com/300/200">
  </div>
  <div class="text-container">
    <div class="titles">
      <h2>Title #1</h2>
    </div>
    <p>lots of words</p>
  </div>
</div>
<div class="flex-container">
  <div class="media-container ">
    <img src="http://www.fillmurray.com/300/200">
  </div>
  <div class="text-container">
    <div class="titles">
      <h2>Title #1</h2>
    </div>
    <p>lots of words</p>
  </div>
</div>

Comments