gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:44:09 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com