【问题标题】:How to align an image of any size from the centre, rather than the top/bottom/sides, using css如何使用 css 从中心对齐任何大小的图像,而不是顶部/底部/侧面
【发布时间】:2012-04-18 15:53:08
【问题描述】:

我希望能够定位图像(蓝色),以便无论大小如何,它始终相对于后面 div 的基线(红色,而不是包含 div)居中。后面的 div 将始终保持相同的大小/位置。

最好只使用 css,因为我使用的是 drupal,而且我对 tpl 文件之外的编辑了解不多。

谢谢!

编辑:这是布局http://pastebin.com/SisQHM4y

【问题讨论】:

  • 到目前为止您尝试过什么?有机会在 jsfiddle.net 上发布一些代码吗?
  • CSS 中的垂直对齐是一件很痛苦的事情。大多数解决方案都是令人讨厌的 hack,需要额外的标记才能工作。
  • @Filype 到目前为止什么都没有,我真的不知道如何处理它。
  • 您要垂直对齐还是水平对齐?
  • 除非知道每张图片的高度,否则我不相信纯 CSS 可以做到这一点。

标签: html css image alignment


【解决方案1】:

嗨,你可以像这样做这个纯 css

css

.wraptocenter {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    width: 500px;
    height: 400px;
    background:green;
}

HTML

<div class="wraptocenter"><img src="//?" alt="images" /></div>

现场演示http://jsfiddle.net/rohitazad/tvrMp/

更多信息http://www.brunildo.org/test/img_center.html

【讨论】:

    【解决方案2】:

    大概是这样的:

    <style>
     #blue { margin-left:auto;margin-right:auto; }
    </style>
    
    <div id="red">
     <div id="blue">
      <img src="?" id="myImg" />
     </div>
    </div>
    

    编辑

    我明白了,所以您希望 x 轴水平居中,而不是垂直居中。而且那个链接有点乱。也许你可以尝试

    <style>
     .user-picture { margin-top: auto; margin-bottom: auto; }
    </style>
    
    
    <div class="content">
    <div class="profile" typeof="sioc:UserAccount" about="/users/diver1">
        <div class="user-picture">
            <a href="/users/diver1" title="View user profile." class="active">
            <img typeof="foaf:Image" src="http://waterworksworldwide.com/sites/default/files/pictures/picture-126-1333572014.gif" alt="Diver1&#039;s picture" title="Diver1&#039;s picture" />
        </a>  
    </div>
    </div>
    

    我仍然很难看到问题中红色和蓝色所暗示的区域之间的重叠位置。如果与我的建议没有重叠,请告诉我,也许我们可以尝试使用position: absolute; 的一些变体

    【讨论】:

    • 我相信 OP 是在询问如何将中心 x 轴沿包含 div 的基线放置,而不是在包含 div 内水平居中。
    • 我正在使用drupal,所以如果不使用一些php(我不熟悉),我就无法更改html布局。目前蓝色不包含在红色 div 中。编辑:@BryanDowning 是的,没错。
    • @BryanDowning - 啊,我误解了那部分。我相信这需要一些 javascript。
    • @Supertod - 如果您无法更改 html 布局,您能否给我们一个实际示例,看看生成的 html 布局是什么样的?
    • @TravisJ - 同意,除非图像的高度一致。
    猜你喜欢
    • 1970-01-01
    • 2017-02-16
    • 2012-04-22
    • 1970-01-01
    • 2018-04-15
    • 2011-11-24
    • 1970-01-01
    • 2010-12-09
    • 2022-01-15
    相关资源
    最近更新 更多