Search code examples
cssborderbox-shadow

How to apply border around shape created by child divs


I have a number of overlapping divs which I am treating as a single shape. The shape needs to be semi-opaque, so I have housed them in a parent div and applied opacity to the parent div like so:

#top_housing_bg_div {
  opacity: 0.55;
  filter: alpha(opacity=55);
}

#top_bg_div {
  z-index: 9999;
  padding: 3px;
  position: absolute;
  width: -webkit-calc(100% - 14px - 9px);
  width: -moz-calc(100% - 14px - 9px);
  width: calc(100% - 14px - 9px);
  top: 7px;
  left: 7px;
  background-color: black;
  color: white;
  font-size: 12px;
  border-radius: 5px;
  overflow: hidden;
}

#logo_bg_div {
  z-index: 9999;
  position: absolute;
  top: 12px;
  left: 12px;
  background-color: black;
  border-radius: 5px;
  overflow: hidden;
  width: 50px;
  height: 50px;
}
<div id="top_housing_bg_div">
  <div id="top_bg_div">
    &nbsp;
  </div>
  <div id="logo_bg_div">
    <!--empty for now-->
  </div>
</div>

I need to have a single border that follows the outline of that semi-opaque shape (as opposed to each sub-div having its own border which encroaches into the semi-opaque body of the other elements) and I have tried - and failed - to do so by using box-shadow on the parent div, setting border etc.

Is it possible to achieve what I'm trying to achieve?


Solution

  • As you already started adding specific values ( height, width, position etc. ) , you can use a pseudo-element to achieve this goal by adding it on top of the smaller div, and so, covering the border of the div.

    See below ( hope i understood correctly what you wanted )

    body {
    margin:0
    }
    
    #logo_bg_div:before {
      height: 20px;
      top: -1px;
      width: calc(100% + 2px);
      background: black;
      position: absolute;
      left: -1px;
      content: "";
    }
    
    
    #top_housing_bg_div {
      opacity: 0.55;
      filter: alpha(opacity=55);
    }
    
    #top_bg_div {
      z-index: 9999;
      padding: 3px;
      position: absolute;
      width: -webkit-calc(100% - 14px - 9px);
      width: -moz-calc(100% - 14px - 9px);
      width: calc(100% - 14px - 9px);
      top: 7px;
      left: 7px;
      background-color: black;
      color: white;
      font-size: 12px;
      border-radius: 5px;
      overflow: hidden;
      border: 1px solid red;
    }
    
    #logo_bg_div {
      z-index: 9999;
      position: absolute;
      top: 12px;
      left: 12px;
      background-color: black;
      border-radius: 5px;
      width: 50px;
      height: 50px;
      border: 1px solid red;
      position: relative
    }
    <div id="top_housing_bg_div">
      <div id="top_bg_div">
        &nbsp;
      </div>
      <div id="logo_bg_div">
        <!--empty for now-->
      </div>
    </div>