如何从伸缩计算中排除第一个子,同时给予它相对于父的位置?



如何在flex计算中定位flex父级下的第一个子级,并根据需要设置其位置?

.mycontainer{
background-color: 
rgb(200,200,200);
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
}
.mycontainer-bar{
width: 20px;
height: 20px;
background-color: red;
position: absolute;
/* The following sticks the bar/box to the top-right of the page, not of container */
top: 0px;
right: 0px;
}
.row{
margin: 5px;
background-color: blue;
width: 80%;
height: 90px;
}
<div class="mycontainer">
<div class="mycontainer-bar">t</div>
<div class="row">r1</div>
<div class="row">r2</div>
</div>

我想把这个红框做成一个工具栏,把它放在父容器的左上角或右上方。

一种方法是,我可以创建容器的两个子元素,其中第一个子元素是工具栏,第二个子元素是所需行的Flex父元素。但是在我开始之前,我真的想知道是否有可能在不需要额外的html内容的情况下使它像我想要的那样工作。

(当我有能力时,我会标记为最佳答案)

我用

position: relative

position: absolute; 
top:0px; 
right:0px;

在红框上。这也有助于不占用任何空间的盒子!

如果我正确理解了您想要放置它的位置,一种方法是使用position:relative并添加margin-left

.mycontainer{
background-color: 
rgb(200,200,200);
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
}
.mycontainer-bar{
width: 20px;
height: 20px;
background-color: red;
position: relative;
margin-left: calc(100% - 20px)
}
.row{
margin: 5px;
background-color: blue;
width: 80%;
height: 90px;
}
<div class="mycontainer">
<div class="mycontainer-bar">t</div>
<div class="row">r1</div>
<div class="row">r2</div>
</div>

最新更新