如何将两个未知尺寸的物品放在一个盒子中心

时间:2016-03-24 16:19:09

标签: html css css3 flexbox

我有一个150像素的方框。我有两个项目。这两个项目的宽度和高度是可变的和未知的。第一个(.label)我希望位于顶部并水平居中。第二个(.image)我想垂直和水平居中。

这是我尝试使用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%;
}

这几乎可以工作,除了我不知道图像的宽度,所以我无法调整以使其保持居中。

我对弹性盒的尝试也出错:

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

2 个答案:

答案 0 :(得分:4)

如果您想保留css,请为transform:translate(-50%,-50%);添加.image

有例子:



.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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

.container {
    height: 300px;
    width: 300px;
    position: relative;
    border: 1px solid black;
}

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

#image {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.box {
  width: 50px;
  height: 50px;
  background-color: lightblue;
}
<div class="container">
  <div class="box" id="label">LABEL</div>
  <div class="box" id="image">IMAGE</div>
</div>