Question

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

Was it helpful?

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.

OTHER TIPS

I'm not sure what problems you're referring to when you say you want to avoid 'distortions', as by far the simplest solution here is to include the image(s) themselves actually in the markup, and then add some styling to make them responsive.

However, you can achieve what you want with your approach (only browser support suffers). You know the ratio that you want the image to display at. First off, remove the width: 100% from the .img div (it's a div, it will fill the horizontal space). Then, add your 50% as padding:

.img {
    padding-bottom: 50%;
}

When you set a height (or vertical padding here) as a percentage, you're actually setting it as a percentage of the width of the parent. That means your .img div will always have padding equal to half of the .content div, which is what you're after.

This is the same approach that's necessary to get fluid videos and iframes working. Check out this CSS Tricks article for a good explanation of what's going on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top