javascript - 水平对齐大于其父 DIV 的图像

标签 javascript jquery html css

我正在开发一个响应式网站,我想要将比父 DIV 更宽的图像水平居中。该图像与其父图像具有相同的高度。图像的宽度与高度成比例,因此可以正确渲染。我无法将图像放入背景图像。

如何使图像水平居中?最好使用 CSS,尽管使用 jQuery 也可以。

<div>
    <img src="...">
</div>

.div {
    height: 220px;
    margin: 0;
    position: relative;
    width: 100%;
}

.div img {
    display: block;
    height: inherit;
    margin: auto;
    max-width: none;
    width: initial;
}

最佳答案

使图像居中的简单方法是使用绝对位置和负translateX的组合:

.div img {
    display: block;
    height: inherit;
    margin: auto;
    max-width: none;
    width: initial;
    position: absolute;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
}

演示: http://jsfiddle.net/fa000nkw/

关于javascript - 水平对齐大于其父 DIV 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29439321/

相关文章:

javascript - 如何使用jquery检查数组中的对象值是否已经存在

javascript - 如何在 Firebase 表上进行联接

javascript - 单击 Leaflet Popup 中的链接并执行 Javascript

html - 条形码扫描仪在 html 字段中输入缓慢的文本

javascript - jQuery 不发送内容类型为 application/json 的 post 请求

javascript - 生成砌体布局,然后对其应用重力

javascript - 如何检测 JavaScript 中的 macOS 命令键

html - 如何将 bootstrap 3 添加到 meteor1.1.0.2 元素

php - JQuery .each 循环概率

javascript - 没有 jQuery 的 Vue.js 中带有固定标题的粘性侧边栏