div中单个元素与display:flex的对齐;

时间:2015-12-15 13:04:59

标签: html css css3 flexbox

这是我在下面的html和css

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

    .my-btn {
        width: 150px;
        height: 50px;
        background-color: #3f729b;
        line-height: 50px;
        text-align: center;
        color: #FFFFFF;
        cursor: pointer;
        display: inline-block;
    }

    <div class="flex">
        <span class="my-btn btn-back">back</span>

        <span class="my-btn btn-download">download</span>

        <span class="my-btn btn-next">next</span>
    </div>

如果所有.my-btn都可见,一切看起来都不错,但如果我想只看到.btn-next,则会保持对齐状态。我怎样才能正确对齐它我试过用

.btn-next {
    align-self: flex-end;
}

但它不起作用。

和想法?

http://jsfiddle.net/ahzc1f41/1/

2 个答案:

答案 0 :(得分:3)

margin-left: auto;添加到.btn-back。这就是它的意图

编辑:将margin-right: auto;添加到btn-backmargin: 0 auto;添加到btn-download,因为当显示其他按钮之一时,它会失败。

JSFIDDLE

HTML

<div class="flex">
    <span class="my-btn btn-back">back</span>

    <span class="my-btn btn-download">download</span>

    <span class="my-btn btn-next">next</span>
</div>

CSS

.flex {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: space-between;
}

.my-btn {
  width: 150px;
  height: 50px;
  background-color: #3f729b;
  line-height: 50px;
  text-align: center;
  color: #FFFFFF;
  cursor: pointer;
  display: inline-block;
}

.btn-next {
  align-self: flex-end;
  margin-left: auto;
}

.btn-download{
  margin: 0 auto;
}

.btn-back{
  margin-right: auto;
}

.btn-download, .btn-back {
  //display: none;      
}

消息来源:http://www.sketchingwithcss.com/samplechapter/cheatsheet.html

答案 1 :(得分:1)

您可以使用margin-left: auto;上的.btn-nextmargin-right: auto;上的.btn-back

<强> DEMO

.flex {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: space-between;
}

.my-btn {
  width: 150px;
  height: 50px;
  background-color: #3f729b;
  line-height: 50px;
  text-align: center;
  color: #FFFFFF;
  cursor: pointer;
  display: inline-block;
}

.btn-next {
  margin-left: auto;
}

.btn-back {
  margin-right: auto;
}

.btn-download, .btn-back {
  display: none;      
}
    <div class="flex">
        <span class="my-btn btn-back">back</span>

        <span class="my-btn btn-download">download</span>

        <span class="my-btn btn-next">next</span>
    </div>