Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need a border for these divs to render correctly?

Tags:

html

css

I have a block of code that looks like this:

<div class="header">
</div>
<div class="right-gradient">
    <div class="left-gradient">
        @RenderBody()
    </div>
</div>

.right-gradient
{
    background: url('Images/RightGradient.png') repeat-y right top transparent;
}
.left-gradient
{
    background: url('Images/RightGradient.png') repeat-y left top transparent;
}

It should result in something like this:

|-------------------|
|##### Header ######|
|-------------------|
|//               \\|
|//    Content    \\|
|//               \\|
|//               \\|
---------------------

However it instead renders like this:

|-------------------|
|##### Header ######|
|-------------------|
|                   |  - Note the extra space here
|//               \\|
|//    Content    \\|
|//               \\|
|//               \\|
---------------------

While trying to figure out where the extra space between the header and the content is coming from, I have discovered that adding a border to my divs actually corrects the problem and removes the offending space between the header and the content.

.right-gradient
{
    background: url('Images/RightGradient.png') repeat-y right top transparent;
    border: 1px red solid;
}
.left-gradient
{
    background: url('Images/RightGradient.png') repeat-y left top transparent;
    border: 1px blue solid;
}

Why is this?

jsfiddle with sample code reproducing the problem

like image 930
Rachel Avatar asked Jan 08 '13 20:01

Rachel


People also ask

What is the purpose of border property in CSS?

The CSS border properties allow you to specify the style, width, and color of an element's border.

How do you put a border on a div in CSS?

You can use: border-style: solid; border-width: thin; border-color: #FFFFFF; You can change these as you see fit, though.

Can we give border to div?

This is a very simple thing to do. Just go to your stylesheet. css and type border: solid black 2px; in your div section.


1 Answers

Simply put, your margins have collapsed. MDN has a explanation of the phenomenon:

If there is no border, padding, inline content, or clearance to separate the margin-top of a block with the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block with the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

Source: https://developer.mozilla.org/en-US/docs/CSS/margin_collapsing

like image 162
cimmanon Avatar answered Sep 24 '22 16:09

cimmanon