【问题标题】:aligning image to be in the center of the div vertically and horizontally将图像垂直和水平对齐到 div 的中心
【发布时间】:2014-05-26 11:51:57
【问题描述】:

这听起来可能很愚蠢,但我在对齐 div 中的图像时遇到了问题。我尝试过使用

-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);

它在 chrome 和 opera 上运行良好。但它在 Firefox 和 safari 中有一点空白。对于 IE,代码似乎不起作用。之后我用这个替换代码以使其居中。

margin: -50% 0 0 -50%;

但图像未在中心垂直对齐。我的问题是为什么以及如何解决这个问题?

欢迎反馈,谢谢

【问题讨论】:

    标签: html css image webkit alignment


    【解决方案1】:

    在使用 css 作为新标准时,中心对齐有时会很棘手,所有使用 html5 语言编写的网页都必须仅使用 css 对齐,否则将无法成功验证为 html5。下面我给大家举个例子: http://jsfiddle.net/zd9z7/

      <div class="div1">
      <img src="" alt="" class="image1">
      </div>
    
     .image1 {
      height:100px;
      width:100px;
      vertical-align:10%;
      background-color:black;
     }
    
      .div1 {
      text-align:center;
      height:200px;
      width:200px;
      background-color:red;
      }
    

    【讨论】:

      【解决方案2】:

      我会将相对位置固定在您的 div 上,然后将您的图像绝对定位在其中。将图像顶部和左侧的值设置为 50%,然后顶部和左侧的边距分别为宽度和高度的一半。

      这里是一个例子:http://jsfiddle.net/gYLf9/

      .holder {width:400px; height:400px; background:red; position:relative;}
      .img {
          position:absolute; 
          height:100px; 
          width:100px; 
          border:1px solid #000; 
          position:absolute; 
          top:50%; 
          left:50%; 
          margin:-50px 0px 0px -50px
          }
      

      显然更改图像的宽度和高度以及边距以适合图像大小。

      【讨论】:

      • 嗨@pconnor,我实际上正在使用百分比来确定宽度和高度以使其流畅。我真的需要更改为像素才能使对齐正确吗?我的代码结构与您上面写的非常相似。边距顶部无法正常工作,因为不是 -50%,而是我必须放置 -32.8% 以使其垂直对齐。只有水平是好的..
      猜你喜欢
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 2011-04-26
      相关资源
      最近更新 更多