如果存在其他div,则为div的CSS宽度

use*_*698 1 html css css3

在下面的HTML,我想指定的宽度.left只有在有.right在div .wrapper,否则应采取全宽.例如,如果有.rightdiv,则宽度.left应为300px,否则应为500px.

我认为这可以使用css +选择器完成,但如果我不确定如何应用于.left.

<div class="wrapper">
    <div class="left"></div>
    <div class="right"></div>
</div>

.wrapper{
    width: 500px;
}

.left{
    width: 300px;
}

.right{
    width: 200px;
}
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以使用:only-child选择器

.left:only-child
{
  width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

如果您不想使用:only-child选择器,可以尝试以下操作

.wrapper
{
  width: 500px;
  min-height: 50px;
}

.left {
    overflow: hidden;
    min-height: 50px;
    border: 1px dashed #f00;
}

.right {
    float: right;
    width: 200px;
    min-height: 50px;
    border: 1px dashed #00f;
}
Run Code Online (Sandbox Code Playgroud)

  • 好方案!在较旧的浏览器上不受支持,但是使用旧浏 (2认同)