如何在图像上放置按钮?

时间:2019-06-18 16:02:33

标签: javascript html css

我想在照片上添加一个“添加”按钮。就像这张照片enter image description here

<div class="row">
        <div th:each="photo : ${photos}" class="col-md-4">
            <div class="thumbnail">
                <img th:src="${photo.path}" style="width: 100%">
                <div class="caption">
                    <p>
                        <button th:class=".add-to-cart"
                            th:onclick="'addPhotoToOrder(' + ${photo.id} + ')'"
                            type="button" class="btn btn-primary" th:text="#{message.add}"></button>
                    </p>

但这是我的结果: enter image description here

3 个答案:

答案 0 :(得分:1)

您可以尝试以下方法(灵活和绝对定位):

.container {
  display: flex;
}

.btn-container {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 300px;
  height: 300px;
}

.btn-container button {
  height: 15px;
}

.container2 {
  position: relative;
  width: 300px;
  overflow: hidden;
}

.btn-container2 {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  transform: translateY(50%);
}

.btn-container2 button {
  display: block;
  margin: auto;
}
<div class="container">
  <img src="https://via.placeholder.com/300">
  <div class="btn-container">
    <button>Button</button>
  </div>
</div>
<br />
<hr />
<br />
<div class="container2">
  <img src="https://via.placeholder.com/300">
  <div class="btn-container2">
    <button>Button</button>
  </div>
</div>

FLEX PRO

实际上 flex 更好,因为它(精确地)放置在中心,而绝对放置时,按钮容器的顶部垂直放置在中心(因此它的中间点)-您可以与之混为一谈(例如top: calc(50% - 7.5px);(在按钮高度为15px的情况下)或类似的东西,但是 flex 可以立即解决。

FLEX CONs

Flexbox仍可能在不同的浏览器中引起问题(例如添加1px“边框”或其他问题)。这可能会导致您的布局发生意外更改。

答案 1 :(得分:0)

使用绝对位置

    position:absolute;
    top:auto;
    right:auto;
    bottom:auto;
    left:auto;

答案 2 :(得分:0)

您可以使用这些HTML和CSS代码在图像上添加按钮。

<body>
    <div class="container">
        <img src="photo-1556924784-f02bd5b5b094.jpg">
        <button class="btn">Button</button>
    </div>
</body>
.container {
    position: relative;
    width: 50%;
  }

.container img {
    width: 100%;
    height: auto;
  }

.container .btn {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    background-color: #555;
    color: white;
    font-size: 16px;
    padding: 12px 24px;
    border: none;
    cursor: pointer;
    border-radius: 5px;
  }

.container .btn:hover {
   background-color: Red;
  }
相关问题