[英]How do I align an item to the right inside a flex container?
我开始使用flex box,但不确定如何在flex容器内设置要放置在右侧的元素? 我试过应用align-self: flex-end
和justify-content: flex-end
没有成功,所以我希望有人可以帮助我吗?
的CSS
.ctn {
background: lightblue;
height: 100px;
padding: 10px;
display: flex;
align-items: center;
}
.btn {
outline: none;
border: none;
color: navy;
background: lightyellow;
height: 50px;
line-height: 50px;
width: 200px;
text-transform: uppercase;
}
Codepen: http ://codepen.io/styler/pen/pvJFA
align-self属性类似于align-items属性:它仅更改其在横轴上的对齐方式(当您使用行方向时是垂直的)。 不是您想要的。
您可以使用justify-content属性。 如果您有2个以上的项目,则它们将均匀地隔开,第一个项目一直到左侧,最后一个项目一直到右侧:
.ctn {
background: lightblue;
height: 100px;
padding: 10px;
display: flex;
align-items: center;
justify-content: space-between;
}
或者,您可以在要一直向右移动的项目上使用左边距。 如果您有两个以上的项目,它将把所有前面的项目一直向左移动:
.btn {
outline: none;
border: none;
color: navy;
background: lightyellow;
height: 50px;
line-height: 50px;
width: 200px;
text-transform: uppercase;
margin-left: auto;
}
将此用作您的Flexbox备忘单: 完整指南
您也可以使用这个方便的工具: FLEXY
更新:至于OP在注释中指出,这并不能完全解决问题,因此这是jsfiddle: link 。 请告诉我是否发布了解决浏览器不一致的代码(FYI,有3个单独的Flex 版本 : 版本 )干扰了您现有的解决方案。
现在,对于您的问题,这里是一个示例代码:
.ctn {
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-direction: normal;
-moz-box-direction: normal;
-webkit-box-orient: horizontal;
-moz-box-orient: horizontal;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-flex-wrap: nowrap;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
-webkit-box-pack: end;
-moz-box-pack: end;
-webkit-justify-content: flex-end;
-ms-flex-pack: end;
justify-content: flex-end;
-webkit-align-content: stretch;
-ms-flex-line-pack: stretch;
align-content: stretch;
-webkit-box-align: start;
-moz-box-align: start;
-webkit-align-items: flex-start;
-ms-flex-align: start;
align-items: flex-start;
}
.btn{
-webkit-box-ordinal-group: 1;
-moz-box-ordinal-group: 1;
-webkit-order: 0;
-ms-flex-order: 0;
order: 0;
-webkit-box-flex: 1;
-moz-box-flex: 1;
-webkit-flex: 0 1 auto;
-ms-flex: 0 1 auto;
flex: 0 1 auto;
-webkit-align-self: auto;
-ms-flex-item-align: auto;
align-self: auto;
}
/*
Legacy Firefox implementation treats all flex containers
as inline-block elements.
*/
@-moz-document url-prefix() {
.ctn {
width: 100%;
-moz-box-sizing: border-box;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.