我有以下布局:嵌套 DIV,外部宽度为 100%,内部宽度固定。内部的使用 margin:auto
居中。
现在我需要为 DIV 设置不同的背景。比如说,内部应该是红色的,而外部的其余部分应该是绿色的。问题是背景需要是半透明(使用 PNG 或 CSS3 的 rgba()
)。所以,内部DIV的背景看起来不是红色的,而是棕色的!这是我的代码:
<div id="outer">
<div id="inner"></div>
</div>
和 CSS
#outer{width:100%;height:50px;background:rgba(0,255,0,0.5)}
#inner{width:800px;height:50px;margin:auto;background:rgba(255,0,0,0.5)}
我尝试在 #outer
中使用 3 个 float DIV。但我无法为其他 2 个 DIV 设置宽度以使 #inner
位于屏幕中央。 width:auto
效果不佳。
我知道这样的布局可以用表格实现;更准确地说,元素具有 display:table-cell
。因此,当我添加另一个“外部”DIV 时,我得到了我需要的结果(表格布局需要 3 个“级别”:table、row、细胞)。 CSS:
#outer2{display:table;width:100%}
#outer{height:50px;display:table-row}
#inner{width:800px;height:50px;background:rgba(255,0,0,0.5)}
#left, #right, #inner{display:table-cell}
#left, #right {background:rgba(0,255,0,0.5)}
和丑陋的 HTML:
<div id="outer2">
<div id="outer">
<div id="left"></div>
<div id="inner"></div>
<div id="right"></div>
</div>
</div>
有没有其他方法可以将 3 个 DIV 排成一行并保持这种“平衡”?或者,也许有一种完全不同的方法来解决原来的问题?我的意思是,问题的出现只是因为透明度! :)
我不喜欢使用 display:table
的解决方案,因为我添加了 3 个额外的 DIV...另外,请不要建议任何使用 JS 的解决方案。
最佳答案
如果您感到急躁并且不介意丢失水平滚动条...
HTML
<section></section>
CSS
body { overflow-x:hidden; }
section {
width:500px;
height:50px;
margin:0 auto;
position:relative;
background:rgba(255,0,0,0.5);
}
section:before, section:after {
top:0;
bottom:0;
content:"";
width:9999px;
position:absolute;
background:rgba(0,255,0,0.5);
}
section:after { left: 100%; }
section:before { right: 100%; }
帽子提示,CSS-Tricks
关于html - 具有半透明背景的 Div 布局问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6110166/