To preface, I understand how to create a BFC, I am confused on what a BFC actually does.
MDN says that
Elements participating in a BFC use the rules outlined by the CSS Box Model
and the spec says that
In a block formatting context, boxes are laid out one after the other, vertically, beginning at the top of a containing block.
MDN gives the example of a floated div that is out of flow, its height independent from the box parent.
<div class="box">
<div class="float">I am a floated box!</div>
<p>I am content inside the container.</p>
</div>
.box {
background-color: rgb(224, 206, 247);
border: 5px solid rebeccapurple;
/* overflow: hidden; */
}
.float {
float: left;
width: 200px;
height: 150px;
background-color: white;
border:1px solid black;
padding: 10px;
}
And then having the box container ending up filling the height of the floated div. once overflow:hidden is declared which creates a BFC.
.box {
background-color: rgb(224, 206, 247);
border: 5px solid rebeccapurple;
overflow: hidden;
}
How does participating in a BFC end up with this outcome? My thought process:
According to MDN's definition, participating in a BFC makes an element adhere to the box model...but don't all elements, even a floated element, adhere to the box model?
According to the spec's definition, all boxes are laid out vertically, but my-floated div and the p tag are side by side.
It seems that a BFC just makes the container fit all elements participating in its BFC, but if this is the case, then how come using a position: absolute instead of a float: left doesn't provide the same outcome of making the container fit the absolutely positioned element?
e.g.
<div class="box">
<div class="abs">I am an absolutely positioned box!</div>
<p>I am content inside the container.</p>
</div>
.box {
background-color: rgb(224, 206, 247);
border: 5px solid rebeccapurple;
overflow: auto;
position: relative;
height: 50px;
}
.abs {
position: absolute;
top: 250px;
left: 100px;
width: 200px;
height: 150px;
background-color: white;
border:1px solid black;
padding: 10px;
}
Could someone explain what the BFC actually does?
Formatting contexts in general establish a set of rules for the layout of their contents.
The rules for Block formatting contexts are that their in-flow contents are laid out vertically one after the other.
In addition, BFCs have a few side-effects, that exist largely to make the rules established for their contents implementable, such as the way they work in the presence of floats inside or next to them.
Taking your points one by one,
According to MDN's definition, participating in a BFC makes an element adhere to the box model...but don't all elements, even a
floated element, adhere to the box model?
Yes they do. MDN does not actual say that it makes them adhere, just that they do adhere. The MDN statement is rather redundant, but not harmful or incorrect.
According to the spec's definition, all boxes are laid out vertically, but my right-floating div and the p tag are side by side.
This is incorrect. The floating div overlaps the p element. Only the inline content of the p element is side by side with the floating div.
It seems that a BFC just makes the container fit all elements participating in its BFC, but if this is the case, then how come
using a position: absolute instead of a float: left doesn't provide
the same outcome of making the container fit the absolutely
positioned element?
As said above, that BFCs contain their floats is best regarded as a side-effect of the BFC, not really what it does.
Finally, although BFCs provide some isolation of their contents from the outside world, it is not complete. For example, inline-block elements establish BFCs for their contents, but their baselines escape this isolation and are used to vertically align the elements with their inline neighbours.
A BFC is a kind of "isolation" to avoid any interaction of the inside and the outside world of an element. From another part of the MDN you can read:
because an element that establishes a new block formatting context will:
contain internal floats.
exclude external floats.
suppress margin collapsing.
Most of the observation you made (box model, absolute, boxes) aren't related to BFC. Just consider the creation of BFC as a way to encapsulate elements inside (mainly float elements because all the other elements are by default "inside"). Of course, this doesn't apply to absolute/fixed elements because they have their own rule that make them out of the flow.
Yes, text cropping 2020.
Luckily a new CSS prop to deal with this mess is on its way, but before it is widely adopted in all browsers (ie11 no longer) will have to deal with trimming the white space above and bellow the text the traditional hacky way.
So in my examples I have 2 elements - a div (block) and a span (inline). Both have ::before and ::after selectors applied to. In one hand the ::before pseudo-element has a negative value margin-bottom (to pull up the main element itself). On the other hand the ::after pseudo-element has a negative value margin-top (to push it up). There is a differense in the results:
Probably it is because of the formatting context.
Anyone who could shed some light on why in the first example the inner (salmon) container remains "hidden behind" the pseudo-elements and in the second example the inner container overlaps them??
Code: https://codepen.io/pollx/pen/MWyvoXm
.box{
box-sizing: border-box;
background: salmon;
/* border: 2px solid blue; */
}
.box::before,
.box::after {
content: " ";
display: block;
height: 5px;
width: 100%;
}
.box::before {
background: red;
margin-bottom: -8px;
}
.box::after {
background: green;
margin-top: -8px;
}
<div class="box">
Box - div
</div>
<br>
<span class="box">
Box - span
</span>
To understand what is happening you need to refer to the painting order algorithm.
The first case is the easiest one and following the painting order we will first paint the background of the div (step (2)) then the background of the pseudo elements (step (4)) then the content of the div (step (7))
If the element is a block, list-item, or other block equivalent:
background color of element unless it is the root element.
then
For all its in-flow, non-positioned, block-level descendants in tree order: If the element is a block, list-item, or other block equivalent:
background color of element.
Then
Otherwise: first for the element, then for all its in-flow, non-positioned, block-level descendants in tree order: ..
The (7) step is too long but there we will be painting the text. (7.2.1.4.1.1.3 the text.)
The second case is a bit tricky because we are dealing with block elements (our pseudo elements) inside an inline element and we need to consider this part of the specification to understand what's happening
When an inline box contains an in-flow block-level box, the inline box (and its inline ancestors within the same line box) are broken around the block-level box (and any block-level siblings that are consecutive or separated only by collapsible whitespace and/or out-of-flow elements), splitting the inline box into two boxes (even if either side is empty), one on each side of the block-level box(es). The line boxes before the break and after the break are enclosed in anonymous block boxes, and the block-level box becomes a sibling of those anonymous boxes. When such an inline box is affected by relative positioning, any resulting translation also affects the block-level box contained in the inline box.
It's not trivial to understand but to resume, your span element will be splitted into 3 elements. One empty element before the ::before another one between the ::before and ::after (containing the text) and a last empty one after the ::after. The 3 elements will be enclosed in anonymous block boxes to have something like the following:
<anonymous_block><span></span></anonymous_block>
::before
<anonymous_block><span>Box - span</span></anonymous_block>
::after
<anonymous_block><span></span></anonymous_block>
adding border and some padding will make this more visible:
.box{
box-sizing: border-box;
background: salmon;
border: 2px solid blue;
padding:0 5px;
}
.box::before,
.box::after {
content: " ";
display: block;
height: 5px;
width: 100%;
margin:5px 0;
}
.box::before {
background: red;
}
.box::after {
background: green;
}
<span class="box">
Box - span
</span>
Now we get back to our painting border and the difference with our first case is that the background of the span will be painted later because it's not done in the step (4) but the step (7)
Otherwise: first for the element, then for all its in-flow, non-positioned, block-level descendants in tree order:
Otherwise, for each line box of that element:
For each box that is a child of that element, in that line box, in tree order:
background color of element.
So we paint the background of both pseudo elements in the step (4) then the background of the span and it's content in the step (7) making the salomon color on the top and no more behind.
Here is the situation:
body {
margin: 0;
background: pink;
color: #fff;
}
.box {
margin-top: 20px;
background: red;
}
.bottom {
text-align: right;
background: green;
animation: animate 2s infinite alternate linear;
}
#keyframes animate {
from {
margin-top: 10px;
}
to {
margin-top: -40px;
}
}
<div class="box">
some content
</div>
<div class="bottom">
other content
</div>
What's happening?
As you may see we have two div without any complex styling (simply background-color). I am making the second div to overlap the first one by applying a negative margin-top. I am expecting to see one completely overlapping the other but this is not the case. The second div is sliding between the content and the background of the first one and it's a strange behavior for me.
The animation has nothing to do here, I simply use it to better show the behavior. We can simply add negative margin without animation and we will have the same thing:
body {
margin: 0;
background: pink;
color: #fff;
}
.box {
margin-top: 20px;
background: red;
}
.bottom {
margin-top:-10px;
text-align: right;
background: green;
}
<div class="box">
some content
</div>
<div class="bottom">
other content
</div>
So my question is : why such behavior?
By the way, we all know that there is some tricky things with CSS that we don't suspect when we face them the first time (like margin-collapsing, background propagation from body to html, white space issue,etc...) but they are clearly explained somewhere and I hope to find an official resource where I can clearly understand this and not only get something like "Maybe this happen because...", "I suspect this related to...", "I think it have something to do with...",etc.
My opinion/explanation about this
I suppose content like text are more important than background and other visual styling so maybe when we have overlapping we place all the text at the top and all the other styling at the bottom, we decide about the order inside each group and then we print the result.
Here is a more complex example:
body {
margin: 0;
background: pink;
color: #fff;
}
div {
font-size: 39px;
line-height: 28px;
margin-bottom: -20px;
font-weight: bold;
}
body :nth-child(1) {
background: red;
border:3px solid brown;
}
body :nth-child(2) {
background: blue;
border:3px solid yellow;
color: #000;
}
body :nth-child(3) {
background: green;
border:3px solid orange;
}
<div>
some content
</div>
<div>
other content
</div>
<div>
more content
</div>
We can clearly see that the visual stack is as follow (starting from bottom to top):
Styling of the first div(background + border)
Styling of the second div(background + border)
Styling of the third div(background + border)
text content of the first div
text content of the second div
text content of the third div
Important notice: Before answering, please note that I am not looking for a fix to this or how to avoid this. By simply adding position:relative the behavior disappear and we can play with z-index to decide about stacking. Am looking to understand why such thing happen.
WARNING: Reading the following information can affect your mental health.
The painting order for the descendants of an element generating a stacking context (see the z-index property) is:
If the element is a root element:
background color of element over the entire canvas.
background image of element, over the entire canvas, anchored at the origin that would be used if it was painted for the root element.
If the element is
a block, list-item, or other block equivalent:
background color of element unless it is the root element.
background image of element unless it is the root element.
column rule of the element.
border of element.
Otherwise, if the element is a block-level table:
table backgrounds (color then image) unless it is the root element.
column group backgrounds (color then image).
column backgrounds (color then image).
row group backgrounds (color then image).
row backgrounds (color then image).
cell backgrounds (color then image).
cell column rule for multi-column.
all table borders (in tree order for separated borders).
Stacking contexts formed by positioned descendants with negative z-indices (excluding 0) in z-index order (most negative first) then
tree order.
For all its in-flow, non-positioned, block-level descendants in tree order:
If the element is a block, list-item, or other block equivalent:
background color of element.
background image of element.
column rule of the element.
border of element.
Otherwise, the element is a table:
table backgrounds (color then image).
column group backgrounds (color then image).
column backgrounds (color then image).
row group backgrounds (color then image).
row backgrounds (color then image).
cell backgrounds (color then image).
cell column rule (multi-column).
all table borders (in tree order for separated borders).
All non-positioned floating descendants, in tree order. For each one of these, treat the element as if it created a new stacking
context, but any positioned descendants and descendants which actually
create a new stacking context are considered part of the parent
stacking context, not this new one.
If the element is an inline element that generates a stacking context, then:
For each line box that the element is in:
Jump to 7.2.1 for the box(es) of the element in that line box (in tree order).
Otherwise: first for the element, then for all its in-flow, non-positioned, block-level descendants in tree order:
If the element is a block-level replaced element, then: the replaced content, atomically.
Otherwise, for each line box of that element:
For each box that is a child of that element, in that line box, in tree order:
background color of element.
background image of element.
column rule of the element.
border of element.
For inline elements:
For all the elements in-flow, non-positioned, inline-level children that are in this line box, and all runs of text inside the
element that is on this line box, in tree order:
If this is a run of text, then:
any underlining affecting the text of the element, in tree order of the elements applying the underlining (such that the deepest
element’s underlining, if any, is painted topmost and the root
element’s underlining, if any, is drawn bottommost).
any overlining affecting the text of the element, in tree order of the elements applying the overlining (such that the deepest
element’s overlining, if any, is painted topmost and the root
element’s overlining, if any, is drawn bottommost).
the text
any line-through affecting the text of the element, in tree order of the elements applying the line-through (such that the deepest
element’s line-through, if any, is painted topmost and the root
element’s line-through, if any, is drawn bottommost).
Otherwise, jump to 7.2.1 for that element
For inline-block and inline-table elements:
For each one of these, treat the element as if it created a new stacking context, but any positioned descendants and descendants
which actually create a new stacking context are considered part of
the parent stacking context, not this new one.
For inline-level replaced elements:
the replaced content, atomically.
Optionally, the outline of the element (see 10 below).
Note, some of the boxes may have been generated by line splitting or the Unicode bidirectional algorithm.
Optionally, if the element is block-level, the outline of the element (see 10 below).
All positioned, opacity or transform descendants, in tree order that fall into the following categories:
All positioned descendants with 'z-index: auto' or 'z-index: 0', in tree order. For those with 'z-index: auto', treat the element as if
it created a new stacking context, but any positioned descendants and
descendants which actually create a new stacking context should be
considered part of the parent stacking context, not this new one. For
those with 'z-index: 0' treat the stacking context generated
atomically.
All opacity descendants with opacity less than 1, in tree order, create a stacking context generated atomically.
All transform descendants with transform other than none, in tree order, create a stacking context generated atomically.
Stacking contexts formed by positioned descendants with z-indices greater than or equal to 1 in z-index order (smallest first) then tree
order.
Now seriously, refer to the w3c paint order documentation
In point 4.1, the background of children is painted
In point 4.4, the border of children is painted.
When point 4 is finished, all background and border of your snippet have been painted
Now, in point 7.2.1.5.1.1.3, the text of the children is painted.
This is the behaviour that you are seeing.
Notice also that is easy to change this behaviour. We can activate point 8.2, (setting opacity) and it will paint like you may have expected:
body {
margin: 0;
background: pink;
color: #fff;
}
.box {
margin-top: 20px;
background: red;
}
.bottom {
text-align: right;
background: green;
animation: animate 2s infinite alternate linear;
opacity: 0.9999;
}
#keyframes animate {
from {
margin-top: 10px;
}
to {
margin-top: -40px;
}
}
<div class="box">
some content
</div>
<div class="bottom">
other content
</div>
Another snippet, showing several point in the document:
Notice that all the border and background in step 4 are rendered after step 3, and before setp 5. But the text in step 4 is step 7, so is rendered after text in step 5
div {
width: 200px;
height: 100px;
border: solid 10px;
font-size: 40px;
}
.step3 {
border-color: red;
background-color: lightpink;
z-index: -1;
position: relative;
margin-left: 10px;
}
.step41 {
border-color: brown;
background-color: yellow;
margin-left: 30px;
margin-top: -40px;
}
.step42 {
border-color: blue;
background-color: lightblue;
margin-left: 50px;
margin-top: -40px;
color: red;
}
.step43 {
border-color: green;
background-color: lightgreen;
margin-left: 160px;
margin-top: -150px;
color: crimson;
}
.step5 {
float: left;
background-color: white;
margin-top: -30px;
}
div:hover {
position: relative;
}
<div class="step3">Step 3 negative zindex</div>
<div class="step41">step4 In flow, number 1</div>
<div class="step42">In flow, number 2</div>
<div class="step43">In flow, number 3</div>
<div class="step5">step 5 float</div>
I don't know if this counts as an use case : this more natural the initial behaviour the the one set by the elements positioning relative
div {
width: 100px;
height: 1.3em;
border: solid 12px tomato;
font-size: 18px;
}
div:hover {
position: relative;
}
<div>a long stretch of text overflowing to the other div</div>
<div></div>
The answer to the question is nowhere near everyone is digging. Because we all have fixed our mind at believing that this is something that leverages user experience anyhow, something intuitive. Have anyone thought this can be for any CPU processing benifit?
Browser rendering engine does not paint an element completely, and then goes on painting the next, because we have GPU technology. The rendering engine paints elements in different stacked layers one over another which are handed over to the GPU who then rasterizes all the layers into a composite layer that shows up on screen.
So, how the layers are created?
Rendering engine paints all backgrounds and borders on the base layer.
Creates a new layer for an element who has positioning specified. The layer is stacked over the base layer for the GPU to rasterize it. When the element moves the rendering engine only tells the GPU to move the layer, GPU does the rest. CPU is saved from painting overhead.
Creates a new layer for an element who has opacity specified. When opacity changes GPU does the rasterizing work.
Similarly creates a new layer for inputs, buttons, canvases, videos everything that can cause CPU to paint repeatedly, is transfered to the GPU as a new layer. We are saving a lot CPU processing, right? :)
Denies creating any new layer for an element with negative margin :( . This is obvious browser cannot issue new layer for every element with margin, there are a lot of them. Even if it has negative margin it may or may not overlap other element. The only way to be sure is to look into the render tree. What's the point? We are trying to save processing, looking into render tree for every element will ruin it.
Issues a new layer for text element. GPU can rasterize text far more efficiently onto a background, so why paint it with CPU on the base layer?? This was the original question. I think everyone can answer it now.
Why text is painted on a separate layer above base layer?
CPU does not need to paint the text over background, CPU is happy.
When text color or shadows change CPU only paints the text layer, GPU rasterizes it on the background.
When the background changes CPU only paints the background layer, GPU rasterizes text over it.
When text is scrolled over a fixed background, no painting is needed, CPU only tells GPU to move the text layer, GPU does the rest.
And a lot more...
Now let's look into the magics we are encountering due to this.
Case 1: When position relative is added to 2nd div it gets a new layer, this new layer is stacked over the base layer and even over the text layer of first div.
Case 2: Same thing happens when opacity is applied.
Case 3: Any transform style will create a new layer.
Case 4: This one is interesting. The margin does not create any layer for the second div, it is painted on the base div after the first div is painted, so it is painted over the first div on the same layer. The text on the first div is on it's own layer that is stacked over the base layer so GPU rasterizes the text over the background of second div.
[source: developers.google.com]
This is because of hierarchy... I will try to explain it a little bit more...
body {
margin: 0;
background: pink;
color: #fff;
}
.box {
margin-top: 20px;
background: red;
}
.bottom {
margin-top:-10px;
text-align: right;
background: green;
}
<div class="box">
some content
</div>
<div class="bottom">
other content
</div>
Like at this your example, our hierarchy looks like:
.box
.box content
.bottom
.bottom content
So, right now if you don't pass position: relative for example, then it will use normal hierarchy of HTML without checking divs...
You have background implemented at .box and .bottom, so at this case when you add margin-top into .bottom, then:
.bottom and .box has same horizontal hierarchy position, but .bottom has bigger vertical, so will overlap .box background
.bottom content and .box content has bigger position than .bottom and .box so will overlap each of them
.bottom content will overlap .box content because of bigger vertical hierarchy
One way to ask the question would be: could it be handled differently and still manage the different features required by CSS, especially the float property?
What the spec says is that for a stacking context (basically the top block of a part of the DOM tree that is positioned), you paint the elements in that order:
background of the top element of the stacking context
elements with z-index negative
Until now it makes sense, then you have
all backgrounds and border of all the block level elements
(basically elements that are display: block but not positioned) in the tree under the top element.
then all floated elements of all the tree under the top element.
This steps in an else from step 2 so it doesn't really interfere with this specific case.
Then all in-flow elements (or non floating elements) of all the tree under top element (it's not just the texts that are rendered in 7, it's all inline elements. If your inline elements has a background, it'll mask what's behind).
The "problem" with this is that is that the in-flow elements are not rendered in the order of the tree. The background of an element lower in the tree can be rendered before an in-flow element upper in the tree. What is implied in the question is that we kind of expect something more like:
render all backgrounds and border and in-flow elements of all the block level elements in tree order.
That would generate the elements in a more intuitive way. So why then separate the in-flow elements from the rest. Why is the step 5 before step 7? It's clear that if you do it that way, then you have a problem with your floating elements. They must be placed before the rest of the flow, because that's what they are, elements that are taken out of the flow. So step 5 makes sense, you need to consider floating elements before non floating elements.
So what if they were rendered in step 4, like this:
all backgrounds and border, then floating and then non floating elements of all the block level elements in tree order.
You still have a problem, because of what is expected of floating elements. See this snippet:
body {
margin: 0;
background: pink;
color: #fff;
}
.box {
margin-top: 20px;
background: red;
}
.bottom {
margin-top:-10px;
text-align: left;
background: green;
}
<div class="box">
<span>some content some content some content some content some content some content some content some content some content some content</span>
<span style="float: left; background: navy">
floated content box<br>
floated content box<br>
floated content box<br>
floated content box
</span>
</div>
<div class="bottom">
<span style="background-color:turquoise;">other content</span>
<span style="float: left; background-color:bisque;">
floated content bottom<br>
floated content bottom<br>
floated content bottom
</span>
</div>
You'll see that the float elements don't have any impact on the height of the block elements, which is expected, else the result would be weird, not at all what's expected of a floating element. So if the floating element in the upper block was rendered before the background of the lower element then the background would be over the floating element. So rendering backgrounds, then float, then in-flow in the tree order doesn't work either. You need to place all float elements of all the tree before you get to the normal flow.
So you're pretty much stuck with this way of handling the render, meaning you have to check all your elements in one context to position floating elements, then position the rest of the normal flow. It has this strange side effect, but considering the complexity of the different positioning expected by the CSS specs, I'm not sure there's another way to do it.
EDIT:
I think this behavior is clearly specified in the specs, see here:
https://www.w3.org/TR/CSS2/visuren.html#floats
The contents of floats are stacked as if floats generated new stacking
contexts, except that any positioned elements and elements that
actually create new stacking contexts take part in the float's parent
stacking context. A float can overlap other boxes in the normal flow
(e.g., when a normal flow box next to a float has negative margins).
When this happens, floats are rendered in front of non-positioned
in-flow blocks, but behind in-flow inlines.
Which means exactly what I've illustrated, meaning that it's expected for floating element to overlap in-flow blocks, and be rendered in front of such backgrounds.
The answer of #vals highlighted where this behavior is explained in the specification BUT provided only 80% of the answer as I am still looking for the why?. Since this behavior is somehow counter-intuitive I tried to find real use cases where this behavior should be like that and not like I expected.
After doing a lot of search, I ended with the logical conclusion that a good web developer should be aware about anything specified within the specification and shouldn't leave a place to random/unexpected behavior especially when it comes to behavior well explained by the specification and not the browser specific ones.
So we write code, we face strange things, we learn about them, we adjust our code ... we do this until we have something working as expected.
Since a web developer has a full control on his development, I was asking my self is there any external tools that may affect his CSS and the rendering of his web page that he cannot control?
Yes, and one of them is related to accessibility.I am not talking about the guidelines a web developer should follow but about some widget in some website that allow you to increase font-size, change contrast, etc in order to help you better read content. This kind of widget can be integrated anywhere using add-ons.
Here a simplified example where a user can increase the font-size and where the above behavior is useful as it will keep the text content above thus we can easily read it:
$('button').click(function() {
$('body').css('font-size','22px');
})
body {
font-size:14px;
max-width:500px;
}
section {
height: 80px;
background: red;
padding:5px;
border-top: 40px solid blue;
color:#fff;
}
div {
height:80px;
background:url(https://lorempixel.com/g/400/400/) center/cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Make font bigger</button>
<section>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam cursus posuere dolor vel faucibus. Proin augue orci, tempor cursus erat aliquet, pellentesque suscipit odio. Sed eleifend diam in justo vehicula feugiat. In pretium, elit eu dapibus efficitur,
</section>
<section>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam cursus posuere dolor vel faucibus. Proin augue orci, tempor cursus erat aliquet, pellentesque suscipit odio. Sed eleifend diam in justo vehicula feugiat. In pretium, elit eu dapibus efficitur,
</section>
<div>
</div>
In this code the developer used a font-size equal to 14px which can be difficult to read for some people so it's logical that we want to increase it. If we do it, we will have the strange behavior BUT if it wasn't like that the content will be hidden and thus we can no more read it!
This situation gives a good reason for such decision and as I said in the question: the content is more important than the styling behind in this case especially when it comes to external tools that change the initial behavior.
The intention of increasing the font-size here is to highlight the content and not the background or border which confirm that the painting order should be like that in order to meet this requirement.
The key to understand why ? is behind understanding the browser painting layers
yesterday I asked the same question and seeking why ?
the first assumption on my question is :
there is an overlapping
but I figure out there is no overlapping at all even when visually we feel that!!
this is better to called intersecting
the moment that I start to shift my mind to believe that was when I read this table on MDN :
**Layer** **Description**
Bottom layer Farthest from the observer
Layer -X Layers with negative z-index values
Layer 0 Default rendering layer
Layer X Layers with positive z-index values
Top layer Closest to the observer
The fact that there is no new stacking context
assure that the elements have been painted on the same layer which is (Layer 0) which mean intersecting not overlapping and this is the point.
the browser wants to finish all backgrounds first? because he know
it's on the same layer
it's the first thing to draw then drawing text
It is important to note that for this case, each div has its height due to its content.
let's say for a moment that the resulting height is 20px.
then, if you say that the first div will have margin-top: 20px, the second div, which was declared after the first, starts from where the first div ends.
so, the initial position of the second would be the margin-top of the first plus the height of the first. let's say that gives 40px.
so, the starting position of the second would be 40px for this case. when you say that the margin-top of the second div is -15px, the initial position would be 40px-15px.
so, if you want the second to overlap the first one, you should place the margin-top equal to the negative of the height of the first.
What happens is that you have 2 overlapping 'boxes' that need to be rendered on the same z layer, layer 0. However, in Introduction to the CSS basic box model, explaining the border area, it says that:
When there is a background (background-color or background-image) set on a box, it extends to the outer edge of the border (i.e. extends underneath the border in z-ordering).
I assume that border and content are both in 'foreground'.
So, the specification of drawing all the boxes on the same layer, combined with the specification of drawing the background underneath the foreground, I guess it results in drawing all the backgrounds underneath all the foregrounds.
Inside each 'sub-layer' the overlapping is according to the HTML order.
To understand why the DIVs in the post are on the same layer, one should read The stacking context.
To 'understand' why the backgroung goes underneath the foreground, one should read Introduction to the CSS basic box model.
I know absolute positioning breaks normal flow but since the order in HTML is absolute element first then static one, I was expecting it to be reflected in the display order too.
.absolute
{
position: absolute;
width: 100px;
height: 100px;
background-color: black;
}
.static
{
background-color: red;
height: 20px;
width: 400px;
}
<div>
<div class="absolute"></div>
<div class="static"></div>
</div>
The reason I need this is because I want to display a sliding menu (the '.absolute' div) which slides from bottom to up and appears like it's coming from the back of the '.static' div.
The container div will obviously need to have 'overflow: visible'.
Any idea how to accomplish this?
Maybe another technique is needed? Like CSS clip?
As per section 9.9.1 Specifying the stack level: the 'z-index' property of CSS 2.2:
Within each stacking context, the following layers are painted in back-to-front order:
the background and borders of the element forming the stacking context.
the child stacking contexts with negative stack levels (most negative first).
the in-flow, non-inline-level, non-positioned descendants.
the non-positioned floats.
the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
the child stacking contexts with positive stack levels (least positive first).
Third one in list is position:static and 6-th is position:absolute. I marked them for you.
Edit, based on your question edits:
In order to fix your issue (which is what you should have asked in the first place, IMHO) you need to
apply position:relative; to your .static div, bringing it to the same level with the position:absolute one. (Now the'll both be positioned).
If the one you want on top is not the last in DOM, you also need to give it a positive z-index, bigger than it's siblings'. Normally they are rendered back-to-top.
Both the answers above give the adequate explanation to the situation you are facing. Given the problem at hand you can use this solution. Just add position:relative to the static div.
.absolute
{
position: absolute;
width: 100px;
height: 100px;
background-color: black;
}
.static
{
background-color: red;
height: 20px;
width: 400px;
position: relative;
}
<div>
<div class="absolute"></div>
<div class="static"></div>
</div>
Absolute position means you can put such div anywhere, and it won’t affect or be affected by any other element in the flow.
Absolutely positioned element is completly removed from the normal flow.
To obtain the effect you want, you might use z-index and position: relative and position: absolute.
I have troubles to understand some very basic css floating rules.
Let's say I have a HTML structure like this:
* {
padding: 0;
margin: 0;
}
div {
width: 200px;
height: 100px;
}
.base {
float: left;
border: 10px solid green;
}
.regular {
height: 50px;
border: 10px solid blue;
}
p {
border: 10px solid red;
}
<div class="base"></div>
<div class="regular"></div>
<p>Some text</p>
Now I don't understand two things:
Why are those two floating elements (div.regular and p) aligned to the left edge of the floated div.base element? I would expect they will be aligned to the right edge so they will be next to the base div element.
Why is the div.base element above all other elements? I would expect it at the bottom since it is before them in the HTML flow.
I would appreciate if you put some light on this for me or give me some resources to understand it.
Both of your questions can be answered by referring to section 9 of the CSS2.1 spec.
Why are those two floating elements (div.regular and p) aligned to the left edge of the floated div.base element? I would expect they will be aligned to the right edge so they will be next to the base div element.
From section 9.5:
Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.
The line boxes refer to the boxes that actually contain the text. In your example, the p element contains one or more line boxes with the words "Some text". Those line boxes are made to reflow around the float. The block box that is generated by the p itself (which in turn contains those line boxes) is laid out as described in the first sentence, simply because block boxes obey different layout rules from line boxes.
Why is the div.base element above all other elements? I would expect it at the bottom since it is before them in the HTML flow.
From section 9.9, emphasis mine:
Within each stacking context, the following layers are painted in back-to-front order:
the background and borders of the element forming the stacking context.
the child stacking contexts with negative stack levels (most negative first).
the in-flow, non-inline-level, non-positioned descendants.
the non-positioned floats.
the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
the child stacking contexts with positive stack levels (least positive first).
Item #3 refers to div.regular and p, since they are in the normal flow, they are block-level, and they are non-positioned. #4 refers to div.base, which is floating.
Elements are painted in source order when
you have multiple elements belonging to the same category, for example when you have two floating elements, or
otherwise not mentioned in this list.
If you want to use float you should have a container, after that you should play with position of elements in css file:
.container{
width: 100%px;
height: 100%px;
border-style: dotted;
}
.base {
border: 10px solid green;
}
.regular {
height: 50px;
border: 10px solid blue;
}
p {
border: 10px solid red;
}
<div class="container">
<div class="base">div1</div>
<div class="regular">div2</div>
<p>Some text</p>
</div>