水平居中对齐宽度可变的图像

时间:2012-02-20 18:54:40

标签: 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;

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

  

[循环]终止;选择器

找到的零元素

有谁知道这意味着什么,以及为什么会这样?此外,如果某人有更好的解决方案来解决这个问题,请分享一下,因为我的机智已经结束了。 :)

4 个答案:

答案 0 :(得分:1)

如果它只是一张图片,为什么你不能在css上text-align:center;

<div style="text-align:center; width:1200px;">
    <img src="img.jpg" />
</div>

答案 1 :(得分:1)

只需使用CSS:

#banner img {
  display: block;

  margin-left: auto;
  margin-right: auto;
}

但是,这不会考虑链接。仅将其应用于#banner也会将其内容集中在其中。

答案 2 :(得分:1)

编辑:(如果图像太大,如果图像太大,则无法使用底部,但这应该是这样)将图像作为标记的背景并将其置于中心位置。

<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>

答案 3 :(得分:1)

你可以使用img tag的块显示和自动边距。

<div style="overflow:hidden; width:1200px;">
<a href="your link"><img src="imagepath" style="margin:auto; display:block" /></a>
相关问题