首页 > 解决方案 > 如何在 CSS(或引导程序)的所有视点上保持按钮居中在图像上?

问题描述

我有一个以我的英雄形象为中心的按钮,但以我目前的方式,我必须使用许多媒体查询来保持它以所有观点为中心。

<style>

 .hero-container{
  position: relative;
  text-align: center;
 }

  .hero-btn-div{
   position: absolute;
   top: 50%;
   left: 42%;
   display: inline-block;
  }

 .hero-btn{
  background-color: transparent;
  font: var(--main-sans-serif);
  font-size: 1.2em;
  border: 1px solid black;
  border-radius: 100px;
  width: 300px;
  height: 50px;
 }

</style>

<div class="hero-container">
  <img src="images/dream%20of%20winter%20cut.jpg" class="img-fluid" width="1920px" alt="Artwork">

  <div class="hero-btn-div"><a href="#"><button class="hero-btn">Button</button></a></div>
</div>

标签: htmlcssbootstrap-5

解决方案


你将更新left:50%并添加这个transform:translateX(-50%;)

 <style>
  .hero-container {
    position: relative;
    text-align: center;
  }

  .hero-btn-div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform:translateX(-50%);
    display: inline-block;
  }

  .hero-btn {
    background-color: transparent;
    font: var(--main-sans-serif);
    font-size: 1.2em;
    border: 1px solid black;
    border-radius: 100px;
    width: 300px;
    height: 50px;
  }
</style>

<div class="hero-container">
  <img src="images/dream%20of%20winter%20cut.jpg" class="img-fluid" width="1920px" alt="Artwork">

  <div class="hero-btn-div"><a href="#"><button class="hero-btn">Button</button></a></div>
</div>

推荐阅读