如何使用Flexbox CSS将每个元素放在一个角落?

时间:2019-06-22 17:54:06

标签: html css flexbox

我正在尝试使用Flexbox在每个角落(左,上,右,下)放置一个链接

我尝试了top: 0或将flex-direction设置为column

.container {
  position: relative;
}

.top {
  display: flex;
  justify-content: space-between;
}

.bottom {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
}
<div class="container">
  <div class="top">
    <a href="one/">ONE</a>
    <a href="two/">TWO</a>
  </div>
  <div class="bottom">
    <a href="three/">THREE</a>
    <a href="four/">FOUR</a>
  </div>
</div>

我希望每个角落都有一个链接,如下图所示:

enter image description here

但是我得到了这个

enter image description here

4 个答案:

答案 0 :(得分:1)

干净,简单的flexbox解决方案(没有黑客或绝对定位):

.container {
  height: 100vh;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between; /* horizontal spacing */
  align-content: space-between;   /* vertical spacing */
}

.top, .bottom {
  flex-basis: 100%;    /* to force .bottom to wrap */
  display: flex;
  justify-content: space-between;
}

a {
  background-color: orange;
}

body {
  margin: 0;
  background-color: lightgray;
}
<div class="container">
  <div class="top">
    <a href="one/">ONE</a>
    <a href="two/">TWO</a>
  </div>
  <div class="bottom">
    <a href="three/">THREE</a>
    <a href="four/">FOUR</a>
  </div>
</div>

答案 1 :(得分:0)

对于这种情况,position: absolute;可能会更好。

.container { position: relative; }

.top-left { position: absolute; top: 0; left: 0 }

.top-right { position: absolute; top: 0; right: 0 }

.bottom-left { position: absolute; bottom: 0; left: 0 }

.bottom-right { position: absolute; bottom: 0; right: 0 }

答案 2 :(得分:0)

这是因为bottomtop div上的高度,默认情况下,它只会占用最小内容的高度,对于包装容器也是如此


这是仅使用flexbox进行修复的一种方法:

.container {
   height: 95vh;
   display: flex;
   flex-direction : column;
   justify-content: space-between;
}

.top {
   display: flex;
   justify-content: space-between;
}

.bottom {
   display: flex;
   justify-content: space-between;
   flex-direction: row;
}
<div class="container">
    <div class="top">
        <a href="one/">ONE</a>
        <a href="two/">TWO</a>
    </div>
    <div class="bottom">
        <a href="three/">THREE</a>
        <a href="four/">FOUR</a>
    </div>
</div>

答案 3 :(得分:0)

您无需在Flexbox中使用.top & .bottom。 Flexbox可以用更少的HTML代码进行处理。

<style>
.container {
    position: relative;
    display: flex;
    flex-flow: row wrap;
    height: 100%;
}

.container a {
    flex: 1 1 50%;
}

.container a:nth-child(2n) {
    text-align: right;
}

.container a:nth-child(3),
.container a:nth-child(4) {
    align-self: flex-end;
}

<div class="container">
    <a href="#">ONE</a>
    <a href="#">TWO</a>
    <a href="#">THREE</a>
    <a href="#">FOUR</a>
</div>