N1ark
N1ark

Reputation: 299

Have background drawn over a div

So I have a div that displays a big title with two lines on its sides that fill the rest of the width.

However now I need to have some text drawn behind this, and because I am drawing the title's bars with background-color they are drawn behind the text.

How can I draw it in such a way that the displayed components from back to front are [bg background-color]->[bg:before]->[title:before/after background-color]->[title]?

Here is the code I have:

#bg
{
  width: 100%;
  height: 100%;
  background-color: silver;
  z-index: -1;
}

#bg:before
{
  content: 'Background';
  position: absolute;
  font-size: 3em;
  color: white;
  user-select: none;
}

#bg *
{
  z-index: 0;
}

.title
{
  display: flex;
  flex-direction: row;
  align-items: center;
}

.title:after, .title:before
{
  content: '';
  width: 50%;
  background-color: black;
  height: 0.2em;
  margin-left: 20px;
  margin-right: 20px;
}

.section_titre h1
{
  font-size: 1em;
  margin: 0px;
}
<div id="bg">
  <div class="title">
    <h1>Example</h1>
  </div>
</div>

Upvotes: 1

Views: 182

Answers (1)

Rayees AC
Rayees AC

Reputation: 4659

The z-index CSS property sets the z-order of a positioned element and its descendants or flex items. Overlapping elements with a larger z-index cover those with a smaller one.

We use z-index

The of Back to front

  • [bg background-color] -> [bg:before] -> [title:before/after background-color] -> [title]

So,

Firstly add z-index(1) to bg background-color

#bg{
  z-index: 1;
  position:relative;// z-index work with other than static position
}

Here,I used position:relative;. Why? Using positioning in z-index?


z-index has no effect on this element since it’s not a positioned element. Try setting its position property to something other than static.


Then add z-index(2) to bg:before

#bg:before {z-index:2;}

Then add z-index(3) to title:before/after background-color

.title:after, .title:before {z-index:3;}

Finally z-index(4) to title

.title{z-index:4;position:relative;}

Working Demo

#bg{
  width: 100%;
  height: 100%;
  background-color: silver;
  z-index: 1;
  position:relative;
}

#bg:before{
  content: 'Background';
  position: absolute;
  font-size: 3em;
  color: white;
  user-select: none;
  z-index:2;
}

.title{
  display: flex;
  flex-direction: row;
  align-items: center;
  z-index:4;
  position:relative;
}

.title:after, .title:before{
  content: '';
  width: 50%;
  background-color: black;
  height: 0.2em;
  margin-left: 20px;
  margin-right: 20px;
  z-index:3;
}

.section_titre h1{
  font-size: 1em;
  margin: 0px;
}
<div id="bg">
  <div class="title">
    <h1>Example</h1>
  </div>
</div>

Upvotes: 2

Related Questions