【问题标题】:Centering images horizontally and vertically within a div of vary width and heighth在不同宽度和高度的 div 中水平和垂直居中图像
【发布时间】:2026-02-18 04:00:02
【问题描述】:

我需要在较大 div 内的图像两侧居中放置一个前进和后退箭头。 div的宽度和高度根据图像的大小而变化。

到目前为止,我在这里有我工作的现场版本:http://danapaigetrentlage.com/cfsa-comps/lff-aboutgoods.html

这里有一个 jsfiddle 可以玩:http://jsfiddle.net/thwackukulele/4zHyd/ 虽然我不知道如果没有链接的图像会有多少用处。

您会看到前进和后退箭头位于图像两侧的蓝色区域顶部。我希望它们在这个蓝色区域内水平和垂直居中。

我知道我使用了很多定位,如果有更好的方法来攻击这种布局,请告诉我。这是我能想到的最好的。我最终会将这些布局交给正在添加数据库 CMS 功能的开发人员。所以我的代码不需要完美,只要说明我的意图,让他理解。

提前感谢您的帮助!

【问题讨论】:

    标签: css positioning css-float


    【解决方案1】:
    .framewrap-fb{ position:relative; }
    .rightarrow, .leftarrow{ position:absolute; top:50%; margin-top:-32px; width:64px; height:64px}
    .leftarrow{left:0}
    .rightarrow{right:0}
    

    【讨论】:

    • 这使我的图像垂直居中,我决定不需要将它们水平居中。我只是要让它们在距 framewrap 的外边缘 30 px 处设置。非常感谢!
    【解决方案2】:

    不确定我是否理解这个问题,需要阅读大量代码,也许只将代码发布在焦点区域。

    试试:

    .wrapper{
           position:relative;
        }
        .left_arrow{
           position:absolute;
           left:0;
           top:50%;
        }
        .right_arrow{
           position:absolute;
           right:0;
           top:50%;
        }
    

    【讨论】:

      【解决方案3】:

      解决方案是将指向 div 的链接绝对定位在 50% 顶部和边缘顶部的负一半链接高度,因此:

      http://jsfiddle.net/elclanrs/JKqnm/

      html:

      <div>
          <img />
          <a id="next"></a>
          <a id="prev"></a>
      </div>
      

      css:

      div {
          position: relative;
          height: 300px; /* Set size */
          width: 500px;
          background: blue;
      }
      #prev, #next {
          position: absolute;
          width: 24px;
          height: 24px;
          top: 50%;
          margin-top: -12px;
          background: red;
      }
      #prev {
          left: -48px;
      }
      #next {
          right: -48px;
      }
      

      【讨论】:

        最近更新 更多