我有一个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%;
}
这几乎可行,除了我不知道图像的宽度,因此我无法调整以使其居中。
我对flex box的尝试也出错了:
.green {
width: 150px;
height: 150px;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
如果你要保持你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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句