lots-to-learn lots-to-learn - 7 months ago 14
HTML Question

How to center two items of unknown dimensions in a box

I have a 150px square box. I have two items in it. The width and height of the two items is variable and unknown. The first (

.label
) I want to be at the top and centered horizontally. The second (
.image
) I want to be centered both vertically and horizontally.

Here's my attempt using
position: absolute
: (jsfiddle)

.container {
width: 150px;
height: 150px;
position: relative;
}
.label {
position: absolute;
width: 100%;
text-align: center;
}
.image {
position: absolute;
top: 50%;
left: 50%;
}


This almost works, except I don't know the width of the image, so I can't adjust to keep it centered.

My attempt with flex box goes wrong as well:

.green {
width: 150px;
height: 150px;
display: flex;
flex-wrap: wrap;
justify-content: center;
}

Answer

If You want to keep Your css then add transform:translate(-50%,-50%); for .image

There is example :

.green {
  background-color: green;
  width: 150px;
  height: 150px;
  position: relative;
}
.label {
  width: 100%;
  text-align: center;
}

.image {
  position: absolute;
  top: 50%;
  left: 50%;
  transform:translate(-50%,-50%); /*go back for 50% of image size left and top*/
}
<div class="green">
  <div class="label">
    Label
  </div>
  <div class="image">
   <img src="http://placehold.it/80x80/0000ff/ffff00" />
  </div>
</div>
<p>
The image should be centered in the box no matter what the width/height of the image.
</p>
<p>
The label should be centered on the top no matter what its width. Normally I'd do something like <code>margin-left: -$half-of-width</code> but I don't know the width. 
</p>