Home > Software engineering >  How to position a div inside a flex item?
How to position a div inside a flex item?

Time:10-31

As I just can't get it right, here is my question:

My DOM looks like this:

<div id="content">
  <div >
    <img />
    <div ></div>
  </div>
  <div >
    <img />
    <div ></div>
  </div>
</div>

CSS:

#content {
  position: absolute;
  overflow: auto;
  width: 100vw;
  top: var(--header-height);
  left:0;
  bottom: var(--footer-height);
  display: flex;
  flex-direction: row;
  place-content: start;
}

.listitem {
  width: var(--image-size);
  height: var(--image-size);
  display: flex;
  flex-direction: row;
}

.thumbnail {
  align-self: flex-start;
  height: var(--image-size);
  width: var(--image-size);
}

.option_icon {
  height: calc(var(--icon-size)*0.75);
  width: calc(var(--icon-size)*0.75);
  background-color: grey;
  mask-image: url("icons/options.svg");
  position: absolute;
  align-self: flex-end;
  z-index: 999;
}

What I want to achieve is that the option icon sticks to the bottom right of every thumbnail image (like a gallery view with square pictures, each one having the option icon on the bottom right.

That works for the first column, but as the options-div is not affected by the flex-grid of the listitems due to being positioned absolutely, all icons get stacked in the first column instead of spreading with their siblings. I'll attach an image to make the current state more clear.

How can I get the red option icons to stay with their siblings that are spread out correctly?

Image of current state

CodePudding user response:

I have achieved your desired result doing the following.

I've added position relative to keep absolute items inside the .listitem. Then I simply added right: 0 to position it on the right end side.

#content {
  position: absolute;
  overflow: auto;
  width: 100vw;
  left: 0;
  display: flex;
  flex-direction: row;
  place-content: start;
}

.listitem {
  width: 60px;
  height: 60px;
  display: flex;
  position: relative;
  flex-direction: row;
}

.thumbnail {
  align-self: flex-start;
  height: 60px;
  width: 60px;
}

.option_icon {
  height: 20px;
  width: 20px;
  background-color: grey;
  mask-image: url("icons/options.svg");
  position: absolute;
  align-self: flex-end;
  z-index: 999;
  right: 0;
}
<div id="content">
  <div >
    <img  />
    <div ></div>
  </div>
  <div >
    <img  />
      <div ></div>
  </div>
</div>

If this is not the result you're looking for, let me know, and I will look into it again.

  • Related