Stefan Walther Stefan Walther - 3 months ago 8
CSS Question

Dynamically align item with CSS

I would like to align a div in the parent container by allowing the user to select the following options:


  • Top Left

  • Top Middle

  • Top Right

  • Left Middle

  • Centered

  • Right Middle

  • Bottom Left

  • Bottom Middle

  • Bottom Right



While I find a lot of resources how to vertically and horizontally align using flexbox, I am wondering if somebody has created a simple collection of CSS-classes I could easily apply.

Edit:

The basic markup is very simple, just a button:

<div>
<div class="btn">This is my button</div>
</div>


Now to get to "Right Middle" I'd ideally to do something like:

<div class="vertical-align-middle horizontal-align-right">
<div class="btn">This is my button</div>
</div>

Answer

Take a look at my example, you need to create classes for every position, then use a little jQuery to make it changed dynamically.

(function() {
  $(".select-box").on("change", function() {
    var $selected = $(this).find("option:selected").val();
    $("#content").removeClass().addClass($selected);
  });
})();
.select-box {
  position: absolute;
  top: 100px;
  left: 100px;
}
#content {
  display: flex;
  width: 600px;
  height: 400px;
  padding: 20px;
}
.box {
  width: 50px;
  height: 50px;
  background-color: fuchsia;
}

#content.top-left {
  justify-content: flex-start;
  align-items: flex-start;
}
#content.top-middle {
  justify-content: center;
  align-items: flex-start;
}
#content.top-right {
  justify-content: flex-end;
  align-items: flex-start;
}
#content.left-middle {
  justify-content: flex-start;
  align-items: center;
}
#content.centered {
  justify-content: center;
  align-items: center;
}
#content.right-middle {
  justify-content: flex-end;
  align-items: center;
}
#content.bottom-left {
  justify-content: flex-start;
  align-items: flex-end;
}
#content.bottom-middle {
  justify-content: center;
  align-items: flex-end;
}
#content.bottom-right {
  justify-content: flex-end;
  align-items: flex-end;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div id="content">
  <div class="box"></div>
</div>
<select class="select-box">
  <option value="top-left">Top Left</option>
  <option value="top-middle">Top Middle</option>
  <option value="top-right">Top Right</option>
  <option value="left-middle">Left Middle</option>
  <option value="centered">Centered</option>
  <option value="right-middle">Right Middle</option>
  <option value="bottom-left">Bottom Left</option>
  <option value="bottom-middle">Bottom Middle</option>
  <option value="bottom-right">Bottom Right</option>
</select>