9b5b
9b5b

Reputation: 1528

Position a variable-width div by it's midpoint

Given a horizontal offset (z), I want to horizontally move variable-width div by it's midpoint to that offset, rather than it's leftmost or rightmost edge.

Since it's variable-width, I cannot simply use half of a fixed-width value to calculate an offset to get the midpoint of the div to (z)

also, the div is absolutely positioned, so it does not take the full width by default

an incorrect example is here:

http://jsbin.com/rejaduxepe/edit?html,css,output

.bar {
  width: 80%;
  position: absolute;
  top: 0;
  height: 25px;
  border-radius: 2px;
  border: solid 1px #F09;
}

.value {
  position: absolute;
  height: 19px;
  line-height: 18px;
  border-radius: 2px;
  top: 2px;
  background-color: #0F9;
  border: solid 1px #F90;
  color: #000;
  left: 20%;
}
<div class="bar">
  <div class="value">123v452</div>
</div>

I do not simply want to center the div value in the center of bar.

I want the "midpoint" of the value div to be 20% from the start of bar, but I don't know how wide the value div is.

The code above puts the "leftmost" portion of value to be 20% from the start of bar, instead of the "midpoint" of value to be 20% from the start of bar

Upvotes: 1

Views: 912

Answers (2)

VXp
VXp

Reputation: 12078

Just add transform: translateX(-50%) which will move it left by half of its width:

.bar {
  width: 80%;
  position: absolute;
  top: 0;
  height: 25px;
  border-radius: 2px;
  border: solid 1px #F09;
}

.value {
  position: absolute;
  height: 19px;
  line-height: 18px;
  border-radius: 2px;
  top: 2px;
  transform: translateX(-50%);
  background-color: #0F9;
  border: solid 1px #F90;
  color: #000;
  left: 20%;
}

span {
  position: absolute;
  top: 30px;
  width: 20%;
  border-top: 2px solid red;
}
<div class="bar">
  <div class="value">123v452</div>
  <span></span>
</div>

Upvotes: 1

Veljko Ilić
Veljko Ilić

Reputation: 161

You can use absolute positioning and translate the elements with or you can use flex on the parent element.

div{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

or

.divWrapper{
  display: flex;
  justify-content: center;
}

Upvotes: 3

Related Questions