Daniels Jirgensons Daniels Jirgensons - 5 months ago 8
CSS Question

Responsive height for images with first child

I made a script whoch get latest news from my website, but now I have problem with design. I dont know why, but my

height:auto
doesnt work and I want the height to work responsively with width, but thats doesn't happen.

Maybe my idea doesn't work with
height:auto
, because there is one bigger image. I tried to made this with max- & min- height, but that doesn't work either.

I need to made this responsive for all screens, I know about media tags, but in media I want to write some little corrections :)

There is my code, maybe someone can help me!?

HTML

<div id="news">

<div id="new_post" style="background-image:url(http://www.dailymobile.net/wp-content/uploads/2012/08/android-640x480-wallpaper-755.jpg)"><a href="" style="color:white">Lorem ipsum dolor sit amet</a></div>
<div id="new_post" style="background-image:url(http://www.dailymobile.net/wp-content/uploads/2012/08/android-640x480-wallpaper-690.jpg)"><a href="" style="color:white">Lorem ipsum dolor sit amet</a></div>
<div id="new_post" style="background-image:url(http://wfiles.brothersoft.com/bd/android_189070-640x480.jpg)"><a href="" style="color:white">Lorem ipsum dolor sit amet</a></div>

</div>


CSS

#new_post{
display: inline-block;
width: 50%;
height: auto;
margin:5px 5px 0 5px;
background-size: cover;
background-position: center center;
}

#new_post:first-child{
float: left;
width: 45%;
height: 205px;
margin: 5px 0 5px 5px;
}


Thanks.

Answer

Is very hard achieve to maintain the aspect ratio in any element but with a image is so easy.

.new_post {
  display: inline-block;
  width: 45%;
  height: auto;
  margin: 5px 5px 0 5px;
  background-size: cover;
  background-position: center center;
}

.new_post:first-child {
  float: left;
  position: relative;
}

.new_post:first-child a {
  position: absolute;
  top: 0
}

.new_post img {
  width: 100%;
}
<div id="news">

  <div class="new_post"><a href="" style="color:white">Lorem ipsum dolor sit amet</a><img src="http://www.dailymobile.net/wp-content/uploads/2012/08/android-640x480-wallpaper-755.jpg"></div>
  <div class="new_post" style="background-image:url(http://www.dailymobile.net/wp-content/uploads/2012/08/android-640x480-wallpaper-690.jpg)"><a href="" style="color:white">Lorem ipsum dolor sit amet</a></div>
  <div class="new_post" style="background-image:url(http://wfiles.brothersoft.com/bd/android_189070-640x480.jpg)"><a href="" style="color:white">Lorem ipsum dolor sit amet</a></div>

</div>