弹性框之间的空间并向右对齐 [英] flexbox space-between and align right

查看:38
本文介绍了弹性框之间的空间并向右对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含1到3个项目的div,我希望它们的行为如下:

I have a div with 1 to 3 items and I want them to behave like this :

  1. 三项:用 justify-content:空格

+-----------+
| 1 | 2 | 3 |
+-----------+

  • 如果只有一项,请将其向右对齐.

  • If there is only 1 item, align it to the right.

    +-----------+
    |       | 3 |
    +-----------+
    

  • 这是我的代码:

    .container {
      display: flex;
      width: 300px;
      justify-content: space-between;
      /* Styling only */
      padding: 10px;
      background: #ccc;
      margin-bottom: 10px;
    }
    .container div {
      /* Styling only */
      background: white;
      padding: 20px 40px;
      width: 10px;
    }

    <div class="container">
      <div>
        1
      </div>
      <div>
        2
      </div>
      <div>
        3
      </div>
    </div>
    
    <div class="container">
      <div>
        3
      </div>
    </div>

    我找到了一种解决方法,其解决方法是 direction:rtl ,但是我希望这里的hacky解决方案少一些,而且我不希望对dom进行重新排序.

    I've found a solution with direction: rtl, but I hope there's a less hacky solution, and I prefer not to reorder my dom.

    有什么想法吗?

    推荐答案

    有一个选择器.

    .container div:only-child {
      margin-left: auto;
    }
    

    .container {
      display: flex;
      width: 300px;
      justify-content: space-between;
      /* Styling only */
      padding: 10px;
      background: #ccc;
      margin-bottom: 10px;
    }
    .container div {
      /* Styling only */
      background: white;
      padding: 20px 40px;
      width: 10px;
    }
    .container div:only-child {
      align-self: flex-end;
      margin-left: auto;
    }

    <div class="container">
      <div>
        1
      </div>
      <div>
        2
      </div>
      <div>
        3
      </div>
    </div>
    
    <div class="container">
      <div>
        3
      </div>
    </div>

    这篇关于弹性框之间的空间并向右对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆