Search code examples
cssbackground-imagesizing

How to size relative div which haven't a content?


I've a HTML markup, where the typographical content are inside of <p>-tags. Between these tags, there I want to place some images. These images are always the same size: 100% wide, 50% high.
To avoid some distortions, I set a <div>-tag with this size and set the image as a background-image with the cover-size.

This <div> doesn't contains any content, except the background-image. So my sizing won't work, because I can't set it to position: absolute / fixed;, beacuase it wouldn't fit anymore between the <p>-tags.

So how I'm able to size the empty div without losing the the fit?

The HTML markup:

<div class="container">
  <section class="about">
    <div class="content">
      <p>Lorem ipsum dolor</p>

      <div class="img"></div>

      <p>Lorem ipsum dolor</p> 
    </div>
  </section>
</div>

And the CSS style

.container,
.container > section{
  position: fixed;
  height: 100%;
  width: 100%;
}
.container > section{
  overflow:auto;
}
.container > section > .content > p{
  padding: 5% 15% 5% 15%;
  font-family: Arial, sans-serif;
  font-size: 1.8em;
  line-height: 1.5;
}
.container > section > .content > .img{
  width:100%;
  height:50%;
  background: url(http://www.hdcarwallpapers.com/walls/widescreen_lamborghini_lp710-wide.jpg) no-repeat center center;
  background-size:cover;
}

And a CODEPEN DEMO


Solution

  • I think the problem is the height. Try removing the 50% height and instead add padding of 50%

    .container > section > .content > .img{
      display: block;
      width:100%;
      padding: 0 0 50% 0;
      background: url(http://www.hdcarwallpapers.com/walls/widescreen_lamborghini_lp710-wide.jpg) no-repeat center center;
      background-size:cover;
    }
    

    Here's a demo.