screampuff February 2016

Auto vertical spacing between random number of elements to fill parent height

I'm looking for a way to auto-fill the space between p elements in a div so that each element is equally spaced, the first one will be on the top margin and last will be on the bottom margin.

Here is a jsfiddle example: https://jsfiddle.net/5b7am7qu/

<div>
  <p>1</p>
  <p>2</p>
  <p>3</p>
</div>

Just say for example that div was set height, how could the first paragraph be on the top margin, bottom paragraph on the bottom margin and then equidistant vertical spacing between every other p element.

I can't give every paragraph an ID or class, but could define first/last-child on the parent.

Answers


SHBelsky February 2016

You could give each p a top & bottom margin in order to make sure they have the same space above and below each of them. You don't need to differentiate between :first-child and :last-child, beacuse the margin will enact itself for all paragraph elements.

.container {
  width: 500px;
  margin: 15px auto;
}
.container div {
  display: table-cell;
  padding: 5px;
}
.left {
  width: 60%;
  background-color: red;
}
.right {
  width: 40%;
  background-color: green;
}
p {
  margin: 10px 0;
}
<div class="container">
  <div class="left">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </div>
  <div class="right">
    <p>
      Paragraph 1
    </p>
    <p>
      Paragraph 2
    </p>
    <p>
      Paragraph 3
    </p>
  </div>
</div>


Nenad Vracar February 2016

You can do this using Flexbox with justify-content: space-between; and flex-direction: column; Fiddle

.right {
  display: flex;
  border: 1px solid black;
  margin: 5px;
  width: 40%;
  height: 200px;
  flex-direction: column;
  justify-content: space-between;
}

p {
  margin: 0;
}
<div class="right">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
</div>

Post Status

Asked in February 2016
Viewed 1,150 times
Voted 11
Answered 2 times

Search




Leave an answer