代码之家  ›  专栏  ›  技术社区  ›  realph

垂直对齐响应方形中的文本块

  •  2
  • realph  · 技术社区  · 12 年前

    我想知道是否有人能帮我解决这个问题。基本上,我试图将位于正方形内的文本块垂直居中。广场很高,因此没有固定的宽度和高度。

    我的HTML格式如下:

    <div class="related-products">
    <div class="row">
        <div class="large-15 medium-15 columns">
    
            <h5>Related Products</h5>
            <div class="row">
    
                <div class="small-15 medium-4 large-4 columns">
                    <div class="product">
                        <a href="/"><img src="http://store.kitchenscookshop.co.uk/media/catalog/product/cache/1/image/500x500/9df78eab33525d08d6e5fb8d27136e95/t/3/t317_mug_red_1pt.jpg"></a>
                        <dl>
                            <dt><a href="/">Product Name is Product Name</a></dt>
                            <dd><del>&pound;29</del> &pound;24</dd>
                        </dl>
                    </div>
                </div>
    
            </div>
        </div>
    </div>
    

    我的CSS是这样的:

    .product {
        position: relative;
        text-align: center;
        display: block;
    }
    
    .product dl {
        background-color: rgba(161,161,161,0.6);
        width: 100%;
        height: 100%;
        padding: 0 20%;
        overflow: auto;
        margin: auto;
        position: absolute;
        top: 0; left: 0; bottom: 0; right: 0;
    }
    

    我还设置了一个演示 over here .

    如果能帮我指明正确的方向,我们将不胜感激。

    提前感谢!

    3 回复  |  直到 12 年前
        1
  •  2
  •   DJ Madeira    12 年前

    不幸地 vertical-align 仅适用于内联元素。这让许多web开发人员感到困惑,因为它看起来应该很容易做到。

    我基本上使用的是这个解决方案: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

    改变 .product dl 的CSS到:

    .product dl {
      background-color: rgba(161,161,161,0.6);
      width: 100%;
      height: auto; /* Won't work without this */
      padding: 0 20%;
      overflow: auto;
      margin: auto;
      position: absolute;
      top: 50%; 
      -webkit-transform:translateY(-50%); 
      /* You may need to add more vendor prefixes; you can use http://prefixmycss.com */
      transform:translateY(-50%);
      z-index:2;
    }
    

    要修复灰色覆盖,我们可以从 .产品dl 并添加此代码:

    .product:after {
      position:absolute;
      display:block;
      content:'';
      background-color: rgba(161,161,161,0.6);
      top:0;
      left:0;
      right:0;
      bottom:0;
      z-index:1;
    }
    
        2
  •  1
  •   Matt    12 年前

    我在您的“.productdl”中添加了“display:table”,看起来效果不错。此外,我认为你的“垂直对齐:中心”是指“垂直对齐,中间”。让我知道你是怎么做的。

        3
  •  0
  •   LOTUSMS    12 年前

    我重新做了一点。我看到你在用桌子,不是我会做的,但我想这很好。校长还是一样。然而,如果您正在从数据库中提取图像,并且无法使用我的方法,那么我使用的css基本原理仍然可以通过简单地将img从后台取出并将其固定到div来使用

    .product {
        background: rgba(161, 161, 161, 0.6) url("http://store.kitchenscookshop.co.uk/media/catalog/product/cache/1/image/500x500/9df78eab33525d08d6e5fb8d27136e95/t/3/t317_mug_red_1pt.jpg") center center no-repeat;
        height:400px;
        padding: 0 20%;
        overflow: auto;
        margin: auto;
     }
    

    FIDDLE

    推荐文章