4

I want to set the width of Image. here is my code :-

<div style="width: 630px;">
        <img src="Image/welcomeimage.jpg" alt="no image" />
  </div>

Here is my situation, I don't have to set the width of Image. Only I can set the width of Div. So I have to set the image width using div. How can I do this?

[Edit] Thanks to all for helping me. Now I solved my problem. Initially, I was told not to use CSS, I had to solved this issue using Inline CSS. But It was not possible. So I decided to use CSS.

3
  • 2
    why can't you set the image width? Commented Apr 23, 2013 at 11:17
  • Do you mean you want to set the width of your image via the width of your div? Commented Apr 23, 2013 at 11:19
  • Whatever you do, you will not come around to set at minimum once styles for the img. If your image would have a width of 100%, then you could set the width with the div. Commented Apr 23, 2013 at 11:20

6 Answers 6

6

Use max-width

You can use the max-width property which is supported in all modern browsers and IE 8 and above.

To use it call it in your css like so:

div img { max-width: 100%; }

This will stretch your image to the div's width.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the only correct answer. Also note that you will have to set box-sizing to border-box if your image has borders
4

Just do this if you want to set the width inline:

<div>
    <img src="Image/welcomeimage.jpg" alt="no image" width="630" />
</div>

Comments

1

Try in css file sth like this:

div img {
    width: 630px;
}

Can you use JavaScript (for example jQuery)?

Comments

1

This works. I never changed img explicitly.

<div class="test" style="width: 630px;">
        <img src="http://i.imgur.com/FIylGsy.jpg" alt="no image" />
</div>

CSS:

.test > *{
    width:100%;
}

Demo

4 Comments

Thanks sonu, but as I said I can't write anything for image.
@Jacob You tell he can use CSS and then give an example in javascript? I'm amazed.
@RajeshBiswas I misunderstood you. I thought you don't want to set any static width for img.
@RajeshBiswas Updated. Is this helpful now?
0

You can se the width of the image dynamically using Javascript:

Pseudo:

var div = document.getElementById("yourDiv");
var width = div.style.height;
yourImg.style.width = width;

Comments

0

Use the following css

img {
    width: 100%;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.