curious1
curious1

Reputation: 14717

How to lower a background image from the top of the containing element?

Here is the html:

<section class="bg">
   <h3>this is heading</h3>
   <div>other content</div>
</section>

I have the following for my background image:

.bg {
   background: url("img/watercolor-bkgrd.png") center top / 100% 75%  no-repeat
}

Now I would like to position the background image slightly lower from the top (for example: 100px) so that h3 heading will not stay on top the background image. How can I make it happen without modifying the html structure? Please note that I have to keep what is already in the above css such as centering the image horizontally, etc.

Upvotes: 0

Views: 1606

Answers (3)

FluffyKitten
FluffyKitten

Reputation: 14312

Just change "top" to "100px" or whatever value you want to move it by.

See this working snippet (where I use 80px):

.bg {
height:400px; /* for testing */
   background: url("http://oi67.tinypic.com/28a11js.jpg") center 80px / 100% 75%  no-repeat
}
<section class="bg">
   <h3>this is heading</h3>
   <div>other content</div>
</section>

This is setting the background-position properties inline in the same way that you are in your own code.

The problem is making sure the image is always under the <h3> element: You could make the <h3> element a fixed height and use the same value for your background position.

Unknown height of h3 element

If you don't know the height of the <h3> element, how about adding the image as background to the <div> underneath the <h3> like this:

.bg div{
    height:400px; /* for testing */
       background: url("http://oi67.tinypic.com/28a11js.jpg") center top / 100% 75%  no-repeat
    }
    <section class="bg">
       <h3>this is heading</h3>
       <div>other content</div>
    </section>

Upvotes: 2

Andrea
Andrea

Reputation: 849

Youre looking for the css property "background-position" (Mozilla Docs)

This allows you to set the initial top and left positions of your background image in the div.

background-position: left top; Just add the following to your .bg class:

background-position: 0 100px;

Upvotes: 1

Paulie_D
Paulie_D

Reputation: 115109

Use the background position offset value.

This does require that you know the height of the element above though.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

h3 {
  height: 60px;
  background: lightblue;
  opacity: .5;
}

.bg {
  height: 100vh;
  background-image: url(http://www.placebacon.net/400/200?image=0);
  background-repeat: no-repeat;
  background-position: center top 60px;
}
<section class="bg">
  <h3>this is heading</h3>
  <div>other content</div>
</section>

Upvotes: 2

Related Questions