Blaze Tama
Blaze Tama

Reputation: 10948

Able to set width % but not height

I'm a beginner in css, and I have tried to find the answer but I couldn't find it. So please bear with me :D

I have a meta in my code (because it's a responsive mobile web), i will show it in case its related to my problem:

<meta name="viewport" content="width=device-width, 
   initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">

This is a part of my code, where I want to change the img width and height with css :

<div id="desc">
    <img alt="" src="images/MallDetail/MallDesc.png">
</div>

So I tried something like this:

#desc img {
    float: left;
    width: 95%;
    height: 50%;
    margin: 0 2.5% 0 2.5%; 
}

Then a weird thing happened: the width is working perfectly, the img width size is 95% of the current width, but the height is not working - it's just not changing (its height should be 50% of the current height).

I also have margin 0 and padding 0 to reset my css.

Why is this happening? What should I do to get things working?

Any help is appreciated, Thanks for your help :D

Upvotes: 1

Views: 3718

Answers (2)

Jason Lydon
Jason Lydon

Reputation: 7180

If width is working correctly, then img only needs the height:auto; And I like to let my imgs fill their parents when building fluid sites, so set the other width and margin on desc. This will work fine if the image is square and you want to maintain the height/width ratio.

#desc {
    float: left;
    width: 95%;
    margin: 0 2.5% 0 2.5%; 
}
#desc img {
  width:100%;
  height:auto;
  display:block;
}

If this isn't the goal, the best way to adjust height is using javascript. I usually apply a ratio to the width to get the height.

jquery

var descImg = $('#desc img')
descImg.height( descImg.width() * 0.5 + 'px' );

Upvotes: 1

Dawood Awan
Dawood Awan

Reputation: 7328

You can't set height using %. The height automatically increases when width increases when using % for width.

you should use min-height: 90px; then height increases based on content inside.

e.g.

    <div id="mainContainer">

       <img src="HelloWorld" alt="" style="width:100%" />
       <div class"newContent">
       <h1>Hello</h1>
    </div>

</div>

CSS:

#mainContainer{
  min-height: 80px;
  width:100%;
}

Upvotes: 1

Related Questions