【问题标题】:Absolute position of text in div that is centered in browser window在浏览器窗口居中的 div 中文本的绝对位置
【发布时间】:2020-10-29 19:17:53
【问题描述】:

当 div 与浏览器窗口的左侧对齐时,相对于 div 绝对定位文本很容易。浏览器窗口的宽度可以改变大小并且文本保持在正确的位置。但是我有一个固定宽度的网页,它始终位于浏览器窗口的中心。无论浏览器窗口的宽度如何,我都有一个以网页为中心的 div。这个 div 包含一个图像。我需要将文本绝对定位在图像之上。我的代码是:

<div id="wrapper">
    <div> <img style="max-width:100%; max-height:100%; display:block;" src="../../assets/logos/skitours_title_756w_100h.gif" alt="Website logo">
        <div class="tour_title"> <h3>This is the title</h3> </div>
    </div>
</div>

#wrapper {
    width:756px;
    height:auto;
    margin: auto auto; 
    margin-bottom:5px;
}

.tour_title {
    font-family:Verdana, Arial, Helvetica, sans-serif;
    font-size:20px;
    font-weight:bold;
    color:#696969;
    display:block;
    position:absolute;
    width:500px;
    top:40px;
    left:20px;
}

无论浏览器窗口的宽度如何,这都会导致图像以网页为中心。

但是文本(tour_title)的绝对定位是相对于浏览器窗口的左侧,而不是图像。无论浏览器窗口的宽度如何,如何更正代码以使文本相对于网页?

【问题讨论】:

    标签: html alignment


    【解决方案1】:

    如果我理解正确,您想让文本相对于 图像。 如果是这种情况,您应该:

    1. 使包装器位置:相对,因此“绝对”文本引用它而不是浏览器/网页。
    2. 使文本 div text-align:center;和宽度:100%;使其与包装器的中心对齐。
    3. 制作顶部:随心所欲。 像这样:
    #wrapper {
        width:756px;
        height:auto;
        margin: auto auto; 
        margin-bottom:5px;
        border-style:solid;
        position:relative;
    }
    
    .tour_title {
        font-family:Verdana, Arial, Helvetica, sans-serif;
        font-size:20px;
        font-weight:bold;
        color:#ff00ff;
        position: absolute;
        text-align:center;
        width:100%;
        top: 50%;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-20
      • 1970-01-01
      相关资源
      最近更新 更多