amdvb
amdvb

Reputation: 209

margin top to div inside another div

I have two divs which have background images and I would like to add margin to the the 2nd div but it is creating white space.

How can I add a top margin while keeping the div inside the other div?

<div class="background">
    <div class="logo">
    </div> 
</div>

.logo {
   background-image: url(image/logo2.png);
   height:40px;
   width:400px;
   margin-left:100px;
   display:block;
   margin-top:20px;
}

.background {
   background-image: url(image/empback.png);
   width:100%;
   height:94px;
   min-width:1345px;
}

Upvotes: 5

Views: 11182

Answers (4)

Johny Gates
Johny Gates

Reputation: 135

How about not changing position and still get desired result?

Add this line to background class:

.background{
    border-top: 1px solid transparent;
}

Upvotes: 1

nmkyuppie
nmkyuppie

Reputation: 1476

Just Go through the code.

By just changing position and top value we can get the result.

.logo{
    position: relative;
    top: 10px;
    background-color: black;
    height: 40px;
    width: 400px;
    margin-left: 100px;
    display: block;
    margin-top: 20px;
}

.background{
     position: absolute;
     background-color: green;
     width: 100%;
     top: 50px;
     height: 94px;
     min-width: 1345px;
}

Upvotes: 2

Mr. Alien
Mr. Alien

Reputation: 157334

You can use overflow: auto on the parent element

.background{
    background: #f00;
    width:100%;
    height:94px;
    min-width:1345px;
    overflow: auto;
}

Demo

Just got a link to share which is related to this issue.


Also, a better approach towards this is instead of using position: absolute; you should use position: relative; with top, left, right and bottom properties, which will not only keep the element in float, it will also save you from positioning other elements in the same block.

Demo 2

Upvotes: 12

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

You can make a use of css position property here.

Sample Code

<div class="background">
    <div class="logo">
    </div> 
</div>

.logo
{
    background-image: url(image/logo2.png);
    height:40px;
    width:400px;
    margin-left:100px;
    display:block;
    position:absolute;
    top:20px;
}

.background
{
    background-image: url(image/empback.png);
    width:100%;
    height:94px;
    min-width:1345px;
    position:relative;
}

remove margin-top:20px; and add position and top property for .logo.

Upvotes: 5

Related Questions