html - 两个绝对 -ley 定位元素之间的边距

标签 html css

我有两个 absolute -ley 定位的容器,像这样...

HTML

<div class=title_container>
   <div class=title>Variable length title</div>
   <div class=title_bg></div>
</div>

<div class=description_container>
   <div class=description>Also variable length description</div>
   <div class=description_bg></div>
</div>

CSS

.title_container {
  position:absolute
}
  .title {
    position:relative; z-index:1;
    color:#FFF;
  }
  .title_bg {
    position:absolute; top:0; left:0;
    background:#0000FF;
    opacity:0.50;
    width:100%; height:100%;
  }

.description_container {
  position:absolute
}
  .description {
    position:relative; z-index:1;
    color:#FFF;
  }
  .description_bg {
    position:absolute; top:0; left:0;
    background:#0000FF;
    opacity:0.50;
    width:100%; height:100%;
  }

为了使透明背景宽度和高度与可变长度文本相匹配,两个容器都必须设置为绝对位置。

现在我需要设置两个容器之间的边距,但我不能只设置容器的顶部参数,因为文本长度可以变化,这意味着如果文本长于一行,透明背景将重叠。

在这种情况下,如何在两个容器之间设置固定的 20 像素边距?

http://jsbin.com/IyUZUg/2/

最佳答案

在两个设置为绝对位置的容器周围添加一个包装器。然后你可以通过包装器控制你的绝对位置。然后容器将漂浮(如果需要)并排堆放。如果您希望它彼此重叠,请移除 float 。

    <div id="contentwrapper">
<div class=title_container>
   <div class=title>Variable length title</div>
   <div class=title_bg></div>
</div>

<div class=description_container>
   <div class=description>Also variable length description</div>
   <div class=description_bg></div>
</div>
</div>

CSS

#contentwrapper{
  position:absolute;
  top: 0;
    left: 0;
}

.title_container, .description_container{
    float: left;
}


.title_container{
   padding-right: 20px;
}
  .title {
    position:relative; z-index:1;
    color:#FFF;
  }
  .title_bg {
    position:absolute; top:0; left:0;
    background:#0000FF;
    opacity:0.50;
    width:100%; height:100%;
  }


  .description {
    position:relative; z-index:1;
    color:#FFF;
  }
  .description_bg {
    position:absolute; top:0; left:0;
    background:#0000FF; 
    opacity:0.50;
    width:100%; height:100%;
  }

fiddle

http://jsfiddle.net/hn2HY/9/

关于html - 两个绝对 -ley 定位元素之间的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19688243/

相关文章:

jquery - 语法错误 : missing ) in before using jQuery

javascript - classList.add() 不会在点击事件中立即激活

css - polymer 如何在滚动时更改工具栏文本大小

html - div 填充有问题吗?

jquery - Tinymce 文本编辑器问题(有一个大字符串)

html - SVG 自动在顶部添加填充并在底部切断

javascript - 通过 innerhtml 分配 ID 时,jquery ui 对话框不会打开

javascript - 为什么 javascript/jQuery 获取不到 parentNode?

javascript - 在同一页面上添加两个 div,每个包含一个链接,隐藏它的父 div 并显示另一个

html - 基于列表的下拉菜单在 IE 中不起作用