【问题标题】:Align HTML element with background img positioned center将 HTML 元素与背景图像位置中心对齐
【发布时间】:2014-02-21 00:50:46
【问题描述】:

我有一个背景图像中心位于身体上,如下所示:

body {
    position:relative;
    width: 100%;
    height: 100%;
    background: url(../img/backgroundMd.jpg) no-repeat center center fixed #000; 
}

我想将 div 对齐图像的一部分。所以它完全覆盖了它(在不同的屏幕分辨率上)

div {
    position:absolute;
    width: 400px;
    height: 320px;
    background-color: black;
    top: ?
    left: ?
}

backgroundMD.jpg 非常大,所以它会离开屏幕。这就是为什么我不能制作一个包装器 div 并将其居中。有什么想法吗?

【问题讨论】:

  • 你能做一个小提琴或草图吗?如果背景图片太大,你可以试试background-size:cover?
  • 充其量你可以使用基于百分比的位置值,但我怀疑你在重新调整屏幕大小时会遇到很多问题。
  • 我在这个答案中对此进行了实验:stackoverflow.com/questions/21829610/… 结论是,您可以做的最好的事情是将<img> 附加到 DOM 以将其用作画布。

标签: html css


【解决方案1】:

如果 div 的尺寸是固定的,你可以这样做

div {
    position:absolute;
    width: 400px;
    height: 320px;
    background-color: black;
    top: 50%;
    left: 50%;
    margin: -200px 0 0 -165px;
}

【讨论】:

    【解决方案2】:

    由于您无法知道背景中的图像在缩放到视口时的高度。您必须将背景添加为<img> 元素。像这样:

    http://jsfiddle.net/NicoO/dLBdv/

    <div class="container">
        <div class="container-canvas">
            <p>Nice to sea you</p>
        </div>
        <img src="http://www.placehold.it/1000x500" /> 
    </div>
    
    
    .container
    {
        position: relative;
    }
    .container > img
    {
        max-width: 100%;
    }
    
    .container > .container-canvas
    {
       background-color:blue;
       background-repeat: no-repeat;
       position: absolute;
       /* % to outer border */
       left:10%;
       top: 10%;
       bottom: 10%;
       right: 10%;
    }
    

    【讨论】:

      【解决方案3】:

      尝试使用此维度 - 这将帮助您将元素保持在页面中间

      div {margin:0 auto;
           width:400px;
           height: 320px;
           background-color: black;}
      

      【讨论】:

      • 您将不得不使用保证金,例如边距:100px 或 200px 自动;如果您制作小提琴,我们可以帮助您
      猜你喜欢
      • 1970-01-01
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多