anthonylawson
anthonylawson

Reputation: 781

CSS Flexbox Centering Horizontally Issue

I have a flexbox container containing 2 div items. The flexbox container is setup for a row that centers the content inside. I am trying to figure out a way to center the contents of the row on the first item, and then have the second item be to the right of the first centered item.

Below is what I ended having to to do: have a the first item centered using the flexbox, but then I have to absolute position the second item to the desired position. Is there a way to remove the absolute positioning of the second item and have it appear just to the right of the first item, which is centered?

HTML

<div class="center-container">
    <div class="time">
        <span id="time">00:00</span>
    </div>
    <div class="time-ampm">
        <span id="time-ampm">XX</span>
    </div>
</div>

CSS

.center-container {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: center;
}

.time {
    flex: 1;
    font-size: 50px;
    font-weight: 300;
    color: #262626;
}

.time-ampm {
    position: absolute;
    top: 115px;
    left: 288px;
    /* flex: 1; <= this is what I want to use, not the absolute positioning used above */
    font-size: 20px;
    font-weight: 400;
    color: #858585;
}

This line shows where the flexbox centers the content if both of the items are set using flexbox (not the absolute positioning as above)

current center

This line shows where I want the flexbox to center the items (centered on the first item)

desired center

Upvotes: 3

Views: 157

Answers (1)

moonbase
moonbase

Reputation: 46

What about setting the offset item width to 0?

HTML:

<div class="container">
  <div>12:20</div>
  <div class="offset">AM</div>
</div>

And CSS:

.container {
  display:flex;
  justify-content: center;
  align-items:baseline;
}
.offset {
  width:0;
}

http://codepen.io/anon/pen/dopQqo

Upvotes: 3

Related Questions