我试图使用flexbox在容器内安排一系列不同的物品,但似乎无法正常使用" pin"一个div到这个容器的右上角。
这里所有元素的相关CSS样式是(为简单起见而修改的类名):
.container {
width: 100%;
display: flex;
flex-wrap: wrap;
align-items: center;
min-height: 3em !important;
}
.teal-items {
margin: 0.25em;
display: inline-block;
height: 36px;
}
.shove-this-in-the-top-right {
margin-left: auto;
margin-right: .5em;
}
我尝试给shove-this-in-the-top-right
隐式display
块,内联或内联块,但无济于事。
答案 0 :(得分:1)
有两种可能的解决方案,如何解决这个问题。第一个是使用浮动物品的包装物和固定物品的包装物。这将是一个明确的解决方案。
第二种解决方案是使用伪元素::after
。您可以在包装器中再次浮动项目并为其提供固定的width
。然后使用伪元素::after
使用position
relative
和absolute
将固定项目放在右上角。这也可能是一种可能的解决方案。看看这些片段,我已经将评论与评论分开了:
/* FIRST SOLUTION WITH WRAPPER FOR FIXED ITEM */
.container {
display: flex;
flex-direction: row;
width: 500px;
border: 1px solid black;
justify-content: space-between;
margin-bottom: 10px;
}
.container__items {
display: flex;
flex-direction: row;
flex-wrap: wrap
}
.container--fixed {
display: flex;
flex-direction: column;
justify-content: flex-start;
}
.container--fixed .container__item {
margin: 0;
background-color: lightblue;
}
.container__item {
padding: 5px;
background-color: lightcoral;
margin-right: 5px;
margin-bottom: 5px;
}
/* SECOND SOLUTION WITH PSEUDO AFTER */
.container--second {
position: relative;
}
.container--second .container__items {
width: 400px;
}
.container--second::after {
content: "Fixed item";
position: absolute;
top: 0;
right: 0px;
background-color: lightblue;
padding: 5px;
}
<!-- FIRST SOLUTION WITH WRAPPER FOR FIXED ITEM -->
<div class="container">
<div class="container__items">
<div class="container__item">Item 1</div>
<div class="container__item">Item 2</div>
<div class="container__item">Item 3</div>
<div class="container__item">Item 4</div>
<div class="container__item">Item 5</div>
<div class="container__item">Item 6</div>
<div class="container__item">Item 7</div>
<div class="container__item">Item 8</div>
<div class="container__item">Item 9</div>
<div class="container__item">Item 10</div>
</div>
<div class="container--fixed">
<div class="container__item">Fixed item</div>
</div>
</div>
<!-- SECOND SOLUTION WITH PSEUDO AFTER -->
<div class="container container--second">
<div class="container__items">
<div class="container__item">Item 1</div>
<div class="container__item">Item 2</div>
<div class="container__item">Item 3</div>
<div class="container__item">Item 4</div>
<div class="container__item">Item 5</div>
<div class="container__item">Item 6</div>
<div class="container__item">Item 7</div>
<div class="container__item">Item 8</div>
<div class="container__item">Item 9</div>
<div class="container__item">Item 10</div>
</div>
</div>