【问题标题】:How to keep absolutely positioned element in place when browser window resized调整浏览器窗口大小时如何将绝对定位的元素保持在原位
【发布时间】:2016-05-08 10:31:38
【问题描述】:

我已将文本绝对定位,使其位于我的标题图像内,但我无法弄清楚当浏览器调整大小时如何防止它移动到标题之外。如果浏览器窗口变小,文本会移到页眉之外,但如果浏览器窗口变大,文本会一直移动到页眉的右侧!

页眉宽 800 像素,高 150 像素,位于浏览器窗口的中间。

这是我的 HTML 代码:

<div id="container">
    <div id="header">
        <img src="images/header.jpg" alt="Site Header Image">
        <h1>Our Site</h1>
        <h2>Catchy slogan...</h2>
    </div>
</div>

这是我的 CSS 代码:

body {
    margin: 0px;
    padding: 0px;
}

#header h1 {
    color: #FFFFFF;
    position: absolute;
    top: 0px;
    left: 305px;
}

#header h2 {
    color: #FFFFFF;
    position: absolute;
    top: 30px;
    left: 330px;
}

#header img {
    width: 800px;
    height: 150px;
    display: block;
    margin-left: auto;
    margin-right: auto;
}

【问题讨论】:

    标签: html css resize css-position absolute


    【解决方案1】:

    这是因为absolute 定位相对于主体起作用,如果它没有任何带有position:relative 的父级

    添加此代码

    #header {
      width:800px; /* define a width to the header container */
      position:relative; /* see note */
      margin:0 auto; /* centers header horizontally */
    }
    

    【讨论】:

      【解决方案2】:

      这里有两个问题:

      1. 绝对定位元素的布局相对于相对定位的父元素。您没有指定 #container#header 是相对定位的,因此所有内容都与 body 对齐 - 可能不是您想要的。

      2. 您的两个容器 div,#container#header 是全浏览器宽度。您想将它们限制为800px,以匹配图像,并将它们与margin: auto 居中:

      #header {
        position: relative;
        width: 800px;
        margin: auto;
      }

      这是一个 Codepen: http://codepen.io/eldarshamukhamedov/pen/dGKJGm

      【讨论】:

        猜你喜欢
        • 2011-07-30
        • 1970-01-01
        • 2017-01-05
        • 1970-01-01
        • 2012-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-19
        相关资源
        最近更新 更多