CSS 在图像上显示按钮

css show button over image

本文关键字:按钮 在图像上显示 CSS      更新时间:2023-09-26

我正在制作一个简单的reactjs应用程序,我需要在图像上放置一个button。我的 html 看起来像:

<div className={"panel-body"}>
    <img className={"img-responsive center-block"}
         src={album.photos.data[0].source} />
    {(this.state.isMouseInsideID === album.id) ? <button>Your Button</button> : null}
</div>

除了按钮显示在图像下方之外,一切都很好。但是我想在图像上方或div中间显示按钮

我怎样才能使这项工作?

make button position relative并使用z-index:也许它会对你有所帮助。

如果要在div 中居中按钮,而div 有一个背景图像。我建议为div 分配背景图像,而不是将图像插入div。看看小提琴:

http://jsfiddle.net/49s505sa/1/

.HTML:

<div id="wrapper">
 <button type="button">Your Button</button>
</div>

.CSS:

#wrapper {
 width: 100%;
 height: 400px;
 border: 1px solid black;
 background: url('http://placehold.it/350x150') /*assign image, for demo purposes */
}
button {
 height: 20px;
 position: relative;
 margin: -20px -50px;
 width: 100px;
 top: 50%;
 left: 50%;
}

所以,在渲染方法内部

var style = {
  backgroundImage: 'url(' + album.photos.data[0].source+ ')'
}
<div className={"panel-body"} style={style}>
    {(this.state.isMouseInsideID === album.id) ? <button>Your Button</button> : null}
</div>

这样,我们将动态地将图像分配给特定的div。并且不必太担心造型。

希望对您有所帮助!

使用 z 索引属性

CSS 中的 z-index 属性控制 元素重叠。就像在,哪一个看起来好像是物理上的 离你更近。Z 索引仅影响具有位置的元素 静态(默认值)以外的值。注意:z 索引仅适用于 定位元素 (位置:绝对、位置:相对或位置:固定)。

img {
position: absolute;
left: 0px;
top: 0px;
z-index: 10;
}