StephenRios
StephenRios

Reputation: 2242

Centering a child in a parent narrower than itself

So I've come up with a way to center children in a parent that is smaller than itself. I'm not to keen on the extra markup it takes to accomplish, and I am wondering if there is a better way to accomplish this, with better meaning less extra markup/styling, or "cleaner" in general.

THE GOAL

Given a parent that is smaller (less wide), put the center of the child element in the center of the parent element dynamically without knowing the width of the child element or the parent element.

MY APPROACH

So my approach uses three nested spans (the element itself is of little consequence).

The first span has a width of 0px and is centered via margin: 0 auto. This gives us the center of the parent container.

The second span has a width of auto, a white-space of nowrap, and a display of inline-block. The display is the key here. This restores the natural width of the child element

the third span has a position of relative, and a left of -50%. This centers the span in relation to the parent by offsetting half of the width of the child in relation to the center of the parent.

THE QUESTION

Is there a cleaner/less "janky" way of doing this?

THE MARKUP

<div class="box">
  <span class="first-wrap">
    <span class="second-wrap">
      <span class="third-wrap">
         This should be centered in relation to the box;
      </span>
    </span>
  </span>
</div>

THE STYLES

.box { 
  border: 1px solid red;
  width: 20px;
  height: 20px;

  margin: 40px auto;
}

.box .first-wrap {
  display: block;
  width: 0px;
  margin: 0 auto;
  border: 1px solid blue;
}

.box .first-wrap .second-wrap {
  display: inline-block;
  white-space: nowrap;
  width: auto;
  border: 1px solid green;
}

.box .first-wrap .second-wrap .third-wrap {
  position: relative;
  left: -50%;
  border: 1px solid black;
}

THE FIDDLE

https://jsfiddle.net/d3w1wom0/

Upvotes: 0

Views: 41

Answers (2)

pjk_ok
pjk_ok

Reputation: 967

Just delete your css and replace with the following:

.box {
display: flex;
justify-content: center;
border: 1px solid black; 
}

If you want to change the width, and center things accordingly you can just add the following to the above .box class:

width: 60%;
margin: 0 auto; 

Upvotes: 1

Ed Dogan
Ed Dogan

Reputation: 275

.box {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 20px;
}

will center your text in the box

Upvotes: 1

Related Questions