javascript - 具有可变宽度的水平居中图像

标签 javascript html css

我一直为此发疯:我有一个结构如下的横幅:

<div id="header-image-wrapper">
    <a href="#content-title" id="header-link">
        <img id="bannerimage" src="image source" />
    </a>
</div>

图像不会始终保持相同的宽度,我的客户希望图像在 div 中水平居中。 div 的最大宽度应为 1200px,并带有 overflow:hidden,这样如果图像大于该宽度,它将居中,并且将剪掉左侧和右侧的多余部分。

我认为这可行的唯一方法是使用 javascript:

var imgWidth = document.getElementById('bannerimage').style.width/ 2;
document.getElementById('bannerimage').style.marginLeft = imgWidth;

但是当我刷新页面时,我得到这个错误:

[cycle] terminating; zero elements found by selector

有谁知道这意味着什么,为什么会这样?另外,如果有人对此问题有更好的解决方案,请分享它,因为我无能为力。 :)

最佳答案

编辑:(如果图像太大,底部的将不起作用,就像你说的,但这个应该)将图像作为 a 标签的背景并将其定位在中心。

<html>
<head>
<style>
#header-image-wrapper {
text-align: center;
width: 1200px;
overflow: hidden;
}
#header-link {
    background-image: url("<Path to Your Image>");
    background-position: center;
    background-repeat: no-repeat;
    display: block;
    width: 1200px;
    height: 300px;
}
</style>
</head>
<body>
<div id="header-image-wrapper">
    <a href="#content-title" id="header-link">
    </a>
</div>
</body>
</html>

我会在这里使用 CSS。给 div 一个 ID,然后使用“text-align: center”相应地设置样式

<head>
<style>
#imgDIV {
text-align: center; //It's not only for text :)
width: 1200px;
overflow: hidden;
}
</style>
</head>
<div id="imgDIV">
   <img src="path to image">
</div>

关于javascript - 具有可变宽度的水平居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9366766/

相关文章:

javascript - 将javascript onclick消息添加到php动态列表

javascript - 如何让div在悬停和点击时下沉

html - 在 mvc 中调整 actionlink 按钮的大小时遇到​​问题

javascript - 断言selenium webdriver Node js

javascript - 生成器在 async() 调用后退出

javascript - 调整 Blogger 的精选帖子小工具以显示特定标签的最新帖子

javascript - 事件页面卸载后,没有在 Chrome 上获取 UDP 套接字的 onReceive 回调

html - Microsoft Edge 处理视口(viewport)高度的方式与其他浏览器不同

html - 将一个 div 居中,宽度与其内容一样

visual-studio - CSS文件不断变化