john doe
john doe

Reputation: 9700

Make Element Appear After Another Element Using Only CSS

I have the following HTML:

<h2 class="brand> </h2>
..
.. (lots of other elements like <img, p, h2 etc) 
..

<div class="reviews">...</div>

How can I use CSS to make the div element with class "reviews" appear after the h2 element with the class "brand". Something like this:

<h2 class="brand> </h2>
<div class="reviews">...</div>
..
.. (lots of other elements like <img, p, h2 etc) 
..

UPDATE: I was able to set the margin-top to negative to make it appear where I wanted but now it looks like it is floating on top of things. I used display:block but still it seems floating on top of things. I want it to occupy space.

The negative margin does not appear correctly since different screen sizes will have different negative margins and they are displaying at different positions.

Thanks!

Upvotes: 4

Views: 6174

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123428

you can play a bit with display: table-* CSS properties: if all elements are wrapped in a common container (e.g. a main element)

<main>
  <h2 class="brand">Title</h2>

   <p>lorem ipsum</p>
   <p>lorem ipsum</p>
   <p>lorem ipsum</p>

   <div class="reviews">reviews</div>
</main>

You can move up the .reviews element like so

main          { display: table; }   
main .brand   { display: table-caption; }
main .reviews { display: table-header-group; }

Codepen : http://codepen.io/anon/pen/XbEBma


Result

enter image description here

Upvotes: 2

Oriol
Oriol

Reputation: 288680

You can use flexbox. It introduces the order property which allows you to reorder flex items:

#wrapper {
  display: flex;          /* Magic begins */
  flex-direction: column; /* Column layout */
}
#wrapper > .brand ~ :not(.reviews) {
  order: 1;               /* Move to the bottom */
}
<div id="wrapper">
  <h2 class="brand">Title</h2>
  <p>Paragraph</p>
  <div>Div</div>
  <div class="reviews">Reviews</div>
</div>

Upvotes: 5

Related Questions