Search code examples
htmlcsspositioncenterelement

Combining absolute positions with centered text


I have a problem with positioning 3 separate text elements within a div.

Here's what I want to achieve

White div is the 'ioitem'

Task, simplified:

  1. The number in the center must be centered, no matter how wide it is. (auto-centered)
  2. The number below must be on the left
  3. The letter below must be on the right

My idea:

  1. Create a parenting container for the number in the center
  2. Place a block element to contain the number, which is also automatically centered as required
  3. Do absolute positioning of other elements within .ioitem.

I used the following code

<div class="ioitem ioitem1">
    <div class="numberContainer">
        <div class="number">1</div>
        <div class="width">3</div>
        <div class="base">D</div>
    </div>
</div>

Styles

.ioitem {
    display: inline-block;
    background-color: white;
    height: 30px;

    margin: 0px 10px 10px 0px;
    padding: 0px 0px 0px 0px;

    position: relative;
}
.ioitem1 {  width: 30px; }
.ioitem > .numberContainer {
    font-size: 12px;
    font-weight: bold;

    position: absolute;
    top: 0;
    left: 0;
}
.ioitem > .number {
    display: block;
    margin: auto;
    text-align: center;
}

What I got is this mess:

The number to be in the center isnt centered and pretty much anything is not being placed as I would wish. I omitted some CSS for sake of brevity.

Please, how could I get the desired result? A list of steps would be enough.

The thing that causes me headache is making the .number´s text to be centered automatically.


Solution

  • Try this CSS table layout, since table cell has the vertical-align features. Note, I reordered the HTML tags slightly, put the number in the middle.

    body {
      background: silver;
    }
    .numberContainer {
      background: white;
      display: table;
      table-layout: fixed;
      height: 90px;
      width: 90px;
      font-size: 30px;
      font-weight: bold;
    }
    .width, .number, .base {
      display: table-cell;
      text-align: center;
    }
    .width, .base {
      vertical-align: bottom;
    }
    .number {
      vertical-align: middle;
      font-size: 60px;
      color: orange;
    }
    <div class="ioitem ioitem1">
      <div class="numberContainer">
        <div class="width">3</div>
        <div class="number">1</div>
        <div class="base">D</div>
      </div>
    </div>

    jsFiddle