SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Set one element width equal to another

    Hi,

    I'd like to set the div width equal to the image width. Here's what I can think of:

    Code:
    <script type="text/javascript">
    window.onload = function ()
    {
    document.getElementById('foo').style.width = document.getElementById('bar').width + 'px';
    }
    </script>
    <div id="foo" style="background:red;"><img id="bar" src="image.jpg"></div>
    It seems to be working, but I'm not sure if it's correct coding.

    Thanks in advance for checking the code or any improvement you suggest!
    Rain lover

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    It works, but normally a div will automatically expand to fix the width of the content that's inside it, so you shouldn't need that script there at all, should you?
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    It works, but normally a div will automatically expand to fix the width of the content that's inside it, so you shouldn't need that script there at all, should you?
    Thanks for the answer, but the div width is always larger than image width as it's a block element. I want them to be equal.

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Rain Lover View Post
    Thanks for the answer, but the div width is always larger than image width as it's a block element. I want them to be equal.
    I just want to point out that using scripting for this is a heavy-handed technique compared with using CSS to achieve the the same result.

    I'm glad it works out for you though.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •