skip to Main Content

I have the following DOM layout:

<div style="background-color:rgba(0, 0, 255, 0.2);outline:1px solid red;display:inline">
  This should be marked
  <div>i want this too</div>
  and this too
</div>

I want to style the outer div that is outlines or colors the background of its whole area, the inner div included, like in the Chrome devtools if you select a part of the DOM:

desired result

My restriction is that I cannot change the styles inside the span, it has always different children (I can write any CSS to the outer span though, that doesn’t change the position/dimensions). Basically I want to replicate the Chrome devtools DOM highlighter.

How to do this?

2

Answers


  1. It works exactly the way you want:

    <span style="background-color:rgba(0, 0, 255, 0.2);outline:1px solid red; display: block;">
      works1
      <div style="display:block">I want this too</div>
      works2
    </span>
    

    Although simply changing the display property of your span will do the trick but I think it is something that you should not do. span can be inside of a div but a div should not be inside of a span.

    Login or Signup to reply.
  2. Why it is happening

    The <span> tag has display: inline property enabled by default. It says the browser to embed text content and child tags with display: inline to text. For example:

    .styled {
      border: 5px dashed deeppink;
      background: #00cccc;
    }
    <p>Lorem <span class="styled">ips<b>um</b></span> dolor sit amet...</p>
    <!-- <b> has display: inline by default -->
    <p>Lorem <span class="styled">ips<div style="font-weight: bold; ">um</div></span> dolor sit amet...</p>
    <!-- <div> has display: block by default, so it has not been styled -->

    Solution

    You can replace this tag by <div> or set display: block; property to it, so your code will look like:

    <span style="background-color: rgba(0, 0, 255, 0.2);
                 outline: 1px solid red;
                 display: block;">
      works1
      <div style="display: block;">I want this too</div>
      works2
    </span>

    Solution 2

    As said in comments to a question, it’s unwelcome to put <div> into a <span>, so you can try this:

    <div style="background-color: rgba(0, 0, 255, 0.2);
                 outline: 1px solid red;">
      works1
      <div>I want this too</div>
      works2
    </div>

    And remember that have display: block; enabled by default, so you do not need to enable it (fixed in solution 2)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search