简体   繁体   English

仅使用CSS使元素出现在另一个元素之后

[英]Make Element Appear After Another Element Using Only CSS

I have the following HTML: 我有以下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". 如何使用CSS使带有“评论”类的div元素出现在带有“品牌”类的h2元素之后。 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. 更新:我能够将margin-top设置为负值,使其显示在我想要的位置,但现在它看起来像是浮在事物之上。 I used display:block but still it seems floating on top of things. 我使用display:block但它似乎仍然漂浮在事物之上。 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! 谢谢!

You can use flexbox. 您可以使用flexbox。 It introduces the order property which allows you to reorder flex items: 它引入了order属性,允许您重新排序flex项:

 #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> 

you can play a bit with display: table-* CSS properties: if all elements are wrapped in a common container (eg a main element) 你可以用display: table-* CSS属性:如果所有元素都包装在一个公共容器中(例如一个main元素)

<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 您可以像这样向上移动.reviews元素

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

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


Result 结果

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM