【问题标题】:Centering texted div with absolute position以绝对位置居中文本 div
【发布时间】:2013-08-01 22:40:07
【问题描述】:

我需要几行文本在图像上水平和垂直居中,我在互联网上阅读了很多但我没有帮助我任何解决方案。

HTML:

<div id="textContainer">
    Preparing for important meeting? <br />
    <b>Drink some coffeee!</b> <br />
    <img src="http://i.imgur.com/me2octq.jpg" />
</div>


<div id="baner">
    <div class="imgBaner"></div>
</div>

CSS:

.imgBaner {
    margin: 0 auto;
    width: 100%;
    height: 460px;
    background: url(http://i.imgur.com/5pijCrS.jpg) no-repeat center;
    position: relative;
}


#textContainer {
    position: absolute;
    font-size: 32px;
    text-align: center;
    z-index: 1;
    color: yellow;
}

我还附上了小提琴:http://jsfiddle.net/vXzKc/

感谢每一个帮助!

【问题讨论】:

    标签: html text position absolute


    【解决方案1】:

    要实现这一点,我相信您至少必须知道文本容器的高度。然后你可以使用顶部/边距组合来解决这个问题。

    据我所知,表格单元格是唯一允许其内容垂直对齐的元素。我不知道为什么,但这可以让你通过使用 display: table-cell 来做一个小骗子

    这是我的解决方法:

    HTML:

    <div class="imgBaner">
        <div id="textContainer">
            Preparing for important meeting? <br />
            <b>Drink some coffeee!</b> <br />
            <img src="http://i.imgur.com/me2octq.jpg" />
        </div>
    </div>
    

    CSS:

    .imgBaner {
        margin: 0 auto;
        height: 460px;
        background: url(http://i.imgur.com/5pijCrS.jpg) no-repeat center;
        display: table-cell;
        vertical-align: middle;
    }
    #textContainer {
        font-size: 32px;
        text-align: center;
        color: yellow;
    }
    

    http://jsfiddle.net/vXzKc/1/

    请注意 display: table-cell 可能无法在旧浏览器中使用,或者可能导致不同的行为。我已经在最新的浏览器(IE、Firefox 和 Chrome)中对其进行了测试,并且似乎在所有这些浏览器中都可以使用。

    【讨论】:

      猜你喜欢
      • 2012-03-28
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 2013-05-02
      • 2016-09-20
      相关资源
      最近更新 更多