简体   繁体   English

在不使用 flexbox 的情况下对齐项目的顶部和底部

[英]Align items top and bottom without using flexbox

There exist two items in a box and I'm trying to align the first item to the top of the box and the last item to the bottom of the box.一个盒子里有两个项目,我试图将第一个项目与盒子的顶部对齐,将最后一个项目与盒子的底部对齐。 I know I can do this easily with flexbox:我知道我可以用 flexbox 轻松做到这一点:

 .container { height: 150px; width: 100%; background-color: lime; display: flex; flex-direction: column; justify-content: space-between; }
 <div class="container"> <div>Top text</div> <div>Bottom text</div> </div>

Unfortunately, the platform I'm using (some old html to pdf generator) doesn't support flexbox.不幸的是,我使用的平台(一些旧的 html 到 pdf 生成器)不支持 flexbox。 Is there another way to do this without using flexbox?有没有另一种方法可以在不使用 flexbox 的情况下做到这一点?

Just you can achieve using position relative and absolute as follow.只是你可以实现使用位置相对和绝对如下。 I hope this will be helpful for you.我希望这对你有帮助。

 .container > div { position: absolute; bottom: 0; } .container > div.top { bottom: inherit; top: 0; } .container { height: 150px; width: 100%; background-color: lime; position:relative; }
 <div class="container"> <div class="top">Top text</div> <div>Bottom text</div> </div>

You can use CSS positioning properties.您可以使用 CSS 定位属性。

 .container { position: relative; height: 150px; width: 100%; background-color: lime; } .container > div { position: absolute; } .container > div:first-child { top: 0; /* optional */ } .container > div:last-child { bottom: 0; }
 <div class="container"> <div>Top text</div> <div>Bottom text</div> </div>

Just note that absolutely positioned elements are removed from the document flow.请注意,绝对定位的元素已从文档流中删除。 This means they don't respect the space occupied by surrounding elements, which can result in overlapping.这意味着它们不尊重周围元素占用的空间,这可能会导致重叠。

Here is another idea considering table where your elements will remain in-flow:这是另一个想法,考虑到您的元素将保持流入的表格:

 .container { height: 150px; width: 100%; background-color: lime; display: table; } .container > div { display:table-row; } .container > div:first-child { height:100%; }
 <div class="container"> <div>Top text</div> <div>Bottom text</div> </div>

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

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