Search code examples
htmlcsstwitter-bootstrapposition

CSS Absolute position on the right covers other elements


I have an div element that has position: absolute;. I want it to always be on the right edge and not cover other elements.

Here is my HTML:

.color2 {
  background-color: #ff0078 !important;
  color: white !important;
}

.colorW {
  background-color: white;
  color: black;
  border: 1px #d4d4d4 dotted;
}

.condition-input {
  display: inline-block;
  padding: 3px 7px;
  line-height: 1;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  border-radius: 10px;
  font-size: 0.9em !important;
  width: 180px;
  height: 19px;
  background-color: #fff200;
  color: black;
}

.condition-button-group {
  position: absolute;
  right: 12px;
}
<div>
  <span class="badge color2">Height</span>
  <span class="badge colorW">==</span>
  <input type="text" class="form-control condition-input" />
  <div class="d-inline condition-button-group">Text</div>
</div>

But on the page I see the following. I don't want the "Text" to cover the left on the input, there should be an indentation. How to fix it?


Solution

  • If you use absolute, your parent div needs to be positioned relative so that the absolutely positioned element is absolute within the parent and not the DOM as a whole (or other ancestors set to relative).

    <div class="wrapper">
        <span class="badge color2">Height</span>
        <span class="badge colorW">==</span>
        <input type="text" class="form-control condition-input"/>
        <div class="d-inline condition-button-group">Text</div>
    </div>
    

    Style:

    .wrapper{
        position:relative;
    }
    .condition-button-group {
       right:0;
       top:0;
    }
    

    Check out this link: Position absolute but relative to parent

    You may need to play with the style a bit to position it exactly where you want, but this is the route to take to do what you are trying to do.