0

I am having an issue aligning an element with flexbox. I know how to align elements in center, right or left. But what I'd like to do is to align an element only 30% away from the right border. How can we control the exact distance between the element and the edge of the container with flexbox? Something like the offset with bootstrap?

I have seen tricks where all elements are aligned to the be flex start and the last element to have margin-left: auto.. but that only aligns it to the far right.

I tried to set margin-right: 30% but on mobile devices it causes issues with other elements aligned to the left.

.container {
  display: flex;
  height: 50px;
}

.aligned {
  margin-left: auto;
  margin-right: 30%;
}
<div class="container">
  <div class="aligned">
    <button>Click me</button>
  </div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
M365 Dev
  • 43
  • 5
  • *I tried to set margin-right: 30% but on mobile devices it causes issues with other elements aligned to the left.* what doesn it mean? – DecPK Sep 01 '21 at 01:56
  • when I shrink the screen size, I don't want it to keep aligning the link to the left, there is so much white space on the right hand side on mobile devices that can be filled, it keeps the space and pushes the elements on the left. – M365 Dev Sep 01 '21 at 01:59
  • I can't reproduce what you are trying to say. If you could add snippet to reproduce this problem. – DecPK Sep 01 '21 at 02:03

2 Answers2

0

Use relative positioning, if you want to keep the element in the document flow.

Use absolute position, if you can remove the element from the document flow.

.container {
  display: flex;
  height: 50px;
  border: 1px solid black;  /* demo purposes only */
}

.aligned {
  position: relative;
  left: 70%;
  transform: translateX(-50%);
}
<div class="container">
  <div class="aligned">
    <button>Click me</button>
  </div>
</div>

More details here: Element will not stay centered, especially when re-sizing screen

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

In the element inside the flexbox - use position : absolute ; (if you want it to be at 30% from left in any situation). And use this left : 30% ; . (You can also use margin-left : 30% ; , because left doesnot works as expected with relative position).