我有2的DIV水平方向排列,彼此相邻和使用包装居中。 我用保证金的权利DIV2从DIV1分开。 DIV2可能没有内容。如果DIV2没有任何内容,我想保证金被忽略和DIV1可以单独居中。
I have 2 DIVs aligned horizontally next to each other and centred using a wrapper. I use margin-right to separate DIV2 from DIV1. DIV2 could have no content. In case DIV2 has no content, i want the margin to be ignored and DIV1 to be centred alone.
这是我的CSS:
#div1 {
display: inline-block;
width: 100px;
border: 1px solid #000000;
margin-left: 200px;
}
#div2 {
display: inline-block;
}
这是HTML:
<div style="text-align:center;">
<div id="div1">Div1</div>
<div id="div2"></div>
</div>
我创建了一个小提琴为你一起玩: http://jsfiddle.net/wfrcG/3/
有没有办法在CSS来实现这一目标没有JavaScript的?
Is there a way in CSS to achieve this without javascript?
您可以使用 :空
伪类来设置保证金 0
,如果是空元素
You could use the :empty
pseudo class to set the margin to 0
if the element is empty.
示例这里
#div2:empty {
margin:0;
}