html - 如何垂直居中对象大于其父对象?

标签 html css

<分区>

我想实现这样的例子: Example

我知道如何通过在 css 中使用背景图像来做到这一点,但我不想这样做,因为对象可以是任何东西。它可以是 img、svg、canvas,甚至是 div。还有其他解决方案吗?

最佳答案

我几年前写过如何做到这一点:

https://codepen.io/vsync/pen/DpmnK

.box{
  position:absolute;  /* or relative */
  /* assume box has height limit lower than the image height */
  height: 100px;
  /* demo-related styles: */
  margin: auto;
  top:0; right: 0; bottom: 0; left: 0;
  background: lightblue;
}

/* The magic: */
.box > img{
  position:relative;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%); 
}
<div class='box'>
  <img src="https://via.placeholder.com/150x150/FF0000" />
</div>

关于html - 如何垂直居中对象大于其父对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57371860/

上一篇:javascript - 如何从复选框标签中的 anchor 显示模态

下一篇:html - 无法将 Bootstrap 列设置为不显示

相关文章:

html - Powershell 脚本转换为 html 并根据数字阈值更改字体/单元格颜色

javascript - js中如何向textarea添加文本

javascript - 防止 CSS 在页面重新加载时刷新

javascript - HTML5 Canvas - 输入类型范围

html - 如何重叠CSS中的顶部div标签

css - 未获取@font-face 中使用的字体文件

html - 如何检查符合 html5/css3 的网页

html - 以固定高度垂直对齐 div 中的内联 block

php - 如何使从数据库中检索到的图像具有响应性?

css - 从 Foundation - Rails 更改选项卡名称