3

I was searching for an html page, where i can acquire Font size of a text in a div to be increased using javascript and at the same time an image placed in that div should not be changed as an when the text size is increased. Below i am pasting the sample html page with a text div and image div with javascript to increase the font size. When we click on the Change font size button it will increase the font size at the same time the image placed inside that div will displace from its initial position. But I should place this image at the same position, no matter how the text size has increased and if the text has overflowed it should go to next column. Please help me to overcome this difficulty.

    <html>
<head>

<style type="text/css">
<!--

div#multicolumn4 {
    -moz-column-width: 150px;
    -moz-column-gap: 20px;
    -webkit-column-width: 250px;
    -webkit-column-gap: 20px;
    column-width: 150px;
    column-gap: 20px;
    height: 900px;
}


-->
</style>

<script>
  function changeFontSize(size)
  {
  debugger;
   var elms = document.getElementsByTagName("span");
   for(var i = 0;i < elms.length;i++)
   {
    var elmsHtml = elms[i].innerHTML;
    var widthFactor = parseInt(elms[i].style.fontSize);
    var FontSize = 0;
    var ln = elmsHtml.length;
    FontSize = Math.ceil(widthFactor +size);
    elms[i].style.fontSize = FontSize;
   }
  }
  function setFontSize(FontSize)
  {
   var elms = document.getElementsByTagName("span");
   for(var i = 0;i < elms.length;i++)
   {
    elms[i].style.fontSize = FontSize;
   }
  }
 </script>
</head>

<body>
    <div>


<div id="multicolumn4" >
<span style='font-size:10px;'>
<h1>The header of the columns</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla at turpis eget nibh ultricies dignissim. Duis luctus euismod turpis. Mauris augue. Aliquam facilisis semper elit. Pellentesque semper hendrerit arcu. Phasellus eleifend commodo justo. Aliquam orci urna, imperdiet sit amet, posuere in, lobortis et, risus. Integer interdum nonummy erat. Nullam tellus. Sed accumsan. Vestibulum orci ipsum, eleifend vitae, mollis vel, mollis sed, purus. Suspendisse mollis elit eu magna. Morbi egestas. Nunc leo ipsum, blandit ac, viverra quis, porttitor quis, dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>
</span>
<div><img id="Image-Maps_5201006280459541" src="images/im1.png" usemap="#Image-Maps_5201006280459541" border="0" width="192" height="256" alt="" />
<span style='font-size:10px;'>
<p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Vestibulum dui turpis, lobortis quis, euismod sed, consectetuer sit amet, nunc. Nam mi. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla at turpis eget nibh ultricies dignissim. Duis luctus euismod turpis. Mauris augue. Aliquam facilisis semper elit. Pellentesque semper hendrerit arcu. Phasellus eleifend commodo justo. Aliquam orci urna, imperdiet sit amet, posuere in, lobortis et, risus. Integer interdum nonummy erat. Nullam tellus. Sed accumsan. Vestibulum orci ipsum, eleifend vitae, mollis vel, mollis sed, purus. Suspendisse mollis elit eu magna. Morbi egestas. Nunc leo ipsum, blandit ac, viverra quis, porttitor quis, dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>

<p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Vestibulum dui turpis, lobortis quis, euismod sed, consectetuer sit amet, nunc. Nam mi. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla at turpis eget nibh ultricies dignissim. Duis luctus euismod turpis. Mauris augue. Aliquam facilisis semper elit. Pellentesque semper hendrerit arcu. Phasellus eleifend commodo justo. Aliquam orci urna, imperdiet sit amet, posuere in, lobortis et, risus. Integer interdum nonummy erat. Nullam tellus. Sed accumsan. Vestibulum orci ipsum, eleifend vitae, mollis vel, mollis sed, purus. Suspendisse mollis elit eu magna. Morbi egestas. Nunc leo ipsum, blandit ac, viverra quis, porttitor quis, dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>

<p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Vestibulum dui turpis, lobortis quis, euismod sed, consectetuer sit amet, nunc. Nam mi. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla at turpis eget nibh ultricies dignissim. Duis luctus euismod turpis. Mauris augue. Aliquam facilisis semper elit. Pellentesque semper hendrerit arcu. Phasellus eleifend commodo justo. Aliquam orci urna, imperdiet sit amet, posuere in, lobortis et, risus. Integer interdum nonummy erat. Nullam tellus. Sed accumsan. Vestibulum orci ipsum, eleifend vitae, mollis vel, mollis sed, purus. Suspendisse mollis elit eu magna. Morbi egestas. Nunc leo ipsum, blandit ac, viverra quis, porttitor quis, dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>

<p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Vestibulum dui turpis, lobortis quis, euismod sed, consectetuer sit amet, nunc. Nam mi. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>


</span>
        <p><button onclick="changeFontSize(1.0)">Change font size (+)</button></p>
        <p><button onclick="changeFontSize(-1.0)">Change font size (-)</button></p>
 </div>
 </div>
 </body>
</html>
andyb
  • 43,435
  • 12
  • 121
  • 150
Krishna
  • 361
  • 2
  • 9
  • 24

3 Answers3

3

This type of layout question has been asked before quite a few times :-)

From a quick read of the links on that thread, it looks like it is not easy to do.

Edit: Right, this one has been bugging me. I figured it was possible with a small amount very large amount of complex JavaScript/jQuery and set about making a demo.

There is still some work to be done, since the <p> that contains the image has been left in a bad way (i.e. full of <span> elements). I also make no promises on the performance of this solution. It seems to work for me OK. Oh and also the Font + link will only work once as the actual size of the font it increases the text to is fixed.

That said, I would really try and find an alternate solution to your problem or even question why you need to fix an image position in this way. It is going against the normal browser re-flow and rules.

Edit: Improved demo that addresses the issues in the comments.

Edit 2: Wow, I did not know how complex the CSS3 column layout must be for browsers! Height is calculated in order to make the columns more or less equal and that means that when I detach the <img> the height is adjusted. This adjusted height will be different if the font-size increases and the <img> is not removed. It's just not possible to determine the height of the result before the <img> is removed and added.

That said, I have made it work with one major condition - that the column has a hard-coded height. I tried to make it work with a browser calculated height (as normal flow rules would dictate) but I think it might be very difficult without a lot more work. The only way I think this might work is moving the <img> element forwards one <span> (i.e. word) at a time until the correct position().top is reached. But that would be incredibly inefficient and probably slow the rendering down so much it will be unusable.

So, here is my final demo which is working in Chrome 11 for me. Sorry I could not reach a complete solution with variable height but as I, and others, have said it really is breaking all the browser layout rules!

Edit 3: When I said "final" demo I clearly didn't mean it. I accept your challenge to actually make this work properly with multiple images and I really hope that this time, I have got it. Please have a look at this new demo (working in Chrome12 for me) which works with the HTML you posted. I must admit that the JavaScript you posted was very complex. So I have re-factored everything to work with multiple images based on my original JavaScript.

Edit 4: Quite a lot of edits now… but I found the bug. For each font increment or decrement the images are moved in the flow and potentially a margin-top added to move the image back to it's original position. But I was not clearing this CSS before re-calculating the position on a subsequent font size change.

The key code added was:

// clear any existing marginTop added on the images
images.each(function() {
    $(this).css('marginTop', 0);
});

I also tidied up the JavaScript a bit more whilst I was there and fixed another bug with removing the <span> elements :-)

Updated jsFiddle demo

And just in case jsFiddle ever disappears, here is the complete solution as one HTML file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[
        $(function(){
            var fontSize = 15;

            // cannot store img.position().top or .left here because it is
            // before the browser has re-flowed the columns, therefore the
            // positions will be incorrect
            var imageTops = new Array;
            var imageLefts = new Array;

            $('#fontUp').click(function() {
                reflow(1);
            });

            $('#fontDown').click(function() {
                reflow(-1);
            });

            function reflow(fontSizeStep) {
                storeImagePositions();
                var fontLimitReached = changeFont(fontSizeStep);
                if (!fontLimitReached) {
                    moveImages();
                }
                return false;
            }

            function changeFont(step) {
                fontSize += step;

                var fontSizeLimitReached = true;

                if (fontSize > 30) {
                    fontSize = 30;
                } else if (fontSize < 15) {
                    fontSize = 15;
                } else {
                    fontSizeLimitReached = false;
                }

                if (!fontSizeLimitReached) {
                    $('p').css({fontSize: fontSize + 'px'});
                }

                return fontSizeLimitReached;
            }

            // initialize store of img top and left positions
            function storeImagePositions() {
                if (imageTops.length == 0) { // only do it once
                    $('img').each(function() {
                        var imgPosition = $(this).position();

                        imageTops.push(imgPosition.top);
                        imageLefts.push(imgPosition.left);
                    });
                }
            }

            function moveImages() {
                // bye bye images
                var images = $('img').detach();

                // clear any existing marginTop added on the images
                images.each(function() {
                    $(this).css('marginTop', 0);
                });


                // spanify paragraphs
                $('#column > p').each(function() {
                    $(this).html('<span>' + $(this).html().replace(/\s\s+/g).replace(/(\s)/g,'</span>$1<span>') + '</span>');
                });

                var imageIndex = 0;

                // iterate words, working out where we can move the img to in the flow and if
                // we find a match, increment the index so that as we continue the each()
                // the next image is evaluated for replacement
                $('#column > p span').each(function() {
                    var wordPosition = $(this).position();
                    var wordLeft = wordPosition.left;

                    if (wordLeft >= imageLefts[imageIndex]) {
                        var wordBottom = wordPosition.top + $(this).height();

                        if (wordBottom > imageTops[imageIndex]) {
                            $(this).before(images[imageIndex]); // move img before this word
                            var newImgTop = $(images[imageIndex]).position().top;
                            $(images[imageIndex]).css({marginTop: imageTops[imageIndex] - newImgTop + 'px'});
                            imageIndex++; // increment index so remainder spans are being evaluated against the next image
                        }
                    }
                });

                // reverse the "spanification"
                $('#column > p').each(function() {
                    $(this).html($(this).html().replace(/<\\?span>/g, '').trim());
                });
            }
        });
    //]]>
    </script>
    <style type="text/css">
    div#column {
        -moz-column-count:6;
        -webkit-column-count:3;
        column-count:3;
        -webkit-column-width:100px;
        -moz-column-width:100px;
        column-width:100px;
        height:500px;
    }

    p {
        margin:0;
        clear:left;
        font-size:15px;
        text-align:justify;
    }

    img {
        float:left;
    }
    </style>
</head>
<body>
    <div><a href="#" id="fontUp" style="margin-right:10px">Font +</a><a href="#" id="fontDown">Font -</a></div>
    <div id="column">
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. <img src="http://www.avatarblast.com/avatars/cool/yoda.jpg" title="yoda" alt="yoda"/>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
        <p>The change of name from <img src="http://www.avatarblast.com/avatars/cool/yoda.jpg" title="yoda" alt="yoda"/> LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion, giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language. It has also been claimed that the language's name is the result of a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>
        <p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Vestibulum dui turpis, lobortis quis, euismod sed, consectetuer sit amet, nunc. Nam mi. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>
        <p>Java EE includes several API specifications, such as JDBC, RMI, e-mail, JMS, web services, XML, etc., and defines how to coordinate them. Java EE also features some specifications unique to Java EE for components. These include Enterprise JavaBeans, Connectors, servlets, portlets (following the Java Portlet specification), JavaServer Pages and several web service technologies.<img src="http://www.avatarblast.com/avatars/cool/yoda.jpg" title="yoda" alt="yoda"/> This allows developers to create enterprise applications that are portable and scalable, and that integrate with legacy technologies. A Java EE application server can handle transactions, security, scalability, concurrency and management of the components that are deployed to it, in order to enable developers to concentrate more on the business logic of the components rather than on infrastructure and integration tasks.</p>
        <p>Java (Indonesian: Jawa) is an island of Indonesia. With a population of 136 million, it is the world's most populous island, and one of the most densely populated regions in the world. It is home to 60% of Indonesia's population. The Indonesian capital city, Jakarta, is in west Java.  Much of Indonesian history took place on Java; it was the centre of powerful Hindu-Buddhist empires, Islamic sultanates, the core of the colonial Dutch East Indies, and was at the centre of Indonesia's campaign for independence. The island dominates Indonesian social, political and economic life.</p>
    </div>
</body>
</html>
Community
  • 1
  • 1
andyb
  • 43,435
  • 12
  • 121
  • 150
  • thanks andyb.. thanks for your efforts. What i want to acquire is that i have an html page to show on iPad, when the user zooms the text size the image within that text should be placed in a fixed position at the same time text should go around image without displacing the image. – Krishna Mar 24 '11 at 07:56
  • Happy to help :-) I had fun hacking that together! Does the demo solve the problem for you? I think it does what you describe when I use Chrome11 on Windows. You will definitely need make the code mode generic to suit your needs as it currently only works with one image. – andyb Mar 24 '11 at 08:34
  • @andby. i was working with your solution it is definitely a helpful code, i had modified it to increase the font size on each click, but unfortunately after the first click it is adding "style=""> style="">" tags to the text. here is the updated javascript snippet. var fontsize=14; fontsize++; $('p').css({fontSize: fontsize+'px'}); – Krishna Mar 24 '11 at 10:12
  • @andby ..and also if we keep on increase the fontsize, the image will start to move.. – Krishna Mar 24 '11 at 10:17
  • Oops! Forgot about the `margin-top` that was being added on each click. I've [updated the demo](http://jsfiddle.net/Kn74j/10/) to take this into consideration. I also moved the `Font +` button to the top to make clicking lots of times easier. Don't forget you will also need to fix the multiple `` elements being added each click :-) If I get time I will try and solve that too. – andyb Mar 24 '11 at 11:02
  • Updated the demo again to remove all the ``s after moving the `` – andyb Mar 24 '11 at 11:17
  • @andby..thanks for your updated demo. but when i had tried to place the some text in multiple columns using.#column { -moz-column-count:3; /* Firefox */ -webkit-column-count:3; /* Safari and Chrome */ column-count:3; -webkit-column-width:100px; column-width:100px; } but using this style the code breaks. the image moves randomly..can we do anything possible with this problem. I had really stuck with this thing. – Krishna Mar 24 '11 at 12:42
  • Yes, this is broken with the column layout. I don't think it is possible to make it work due to the re-formatting the browser will do when layout out the columns. I'll see if I can get it working either today or tomorrow but I wouldn't count on it working flawlessly. You really should consider changing your requirements as this really goes against what every browser does naturally. – andyb Mar 24 '11 at 13:51
  • @andby. i am in a really bad situation to achieve it anyway. i will keep on working with your codes. and will update you if i acquire any progress..and also i would really appreciate your help in this problem.. – Krishna Mar 24 '11 at 14:11
  • @andby. Thanks for your improved demo. It helped me a lot. I had modified your code to get it works with image in any paragraph and also with multiple images. But when i added multiple images, after some clicks(increasing font size) it breaks. Can you help me solve this. i am pasting the improved code in my post. – Krishna Mar 26 '11 at 07:56
  • I will try to come up with a solution based on your modified code. However, on first inspection I see there is a lot of duplication! If you ever find yourself copy/pasting code and modifying only a small part, then please consider re-factoring the code. It may be the case that a parameterized function will be more readable and a better solution. – andyb Mar 26 '11 at 20:03
  • Added an updated demo in the solution above which I think is working the way you want it. However, once again I cannot stress how crazy this seems. It really does interfere with normal browser flow and I make no promises about the performance hit of re-organising the DOM in JavaScript or ``ing and un``ing the paragraphs! – andyb Mar 27 '11 at 01:51
  • @andby. I understand my code was duplicated a lot, i will definitely try to minimize the mistakes in future. But When i debug your code, i found at somepoint second image didnt get replaced to initial position as the wordPosition(wordLeft and wordBottom) couldnt match with the imageLefts and imageTops. So it disappears after few clicks. Infact this was one of the major problem with my previous codes also. For making the paragraphs more simple i had added this style {height: 600px;}. Is there any work around for this problem. – Krishna Mar 27 '11 at 07:18
  • @andby. One more thing i would like to add with this. when i decrease the height to 500 px; it worked with Chrome but didnt worked for FF-3. There also i found the same problem the second image disappears after few clicks means wordPosition didnt matched with imagePositions. – Krishna Mar 27 '11 at 07:20
  • Does changing `wordLeft == imageLefts[imageIndex]` to `wordLeft >= imageLefts[imageIndex]` help? I don't have FF3 so cannot test it. As I said, I have only tested this in Chrome12. I am certain that FF and Chrome are laying out the columns slightly differently therefore the comparison logic might not find an exact match. If this simple change does not work I recommend you build in some tolerance into the function so the logic can find a match even if the image position has been rendered in a slightly different position. – andyb Mar 27 '11 at 07:44
  • @andby. thanks. your modification has made it work with Chrome, since my target device is an iPad, I should get it work in safari browser, there I found some strange behavior. Whenever i place an image in the second column after a click it get slipped off from its initial position and jumps to the bottom of the first column. So I changed the css style from float:left to float:inherit. In this case it didnt slipped from its position, but a jerking to the image happens everytime. – Krishna Mar 29 '11 at 05:08
  • I am not sure what I am missing, and also as you said we cannot fully recommend this solution. Is there any way that we can improve this, I found one iPad appliance(Economist magazine) has already achieved this. – Krishna Mar 29 '11 at 05:09
  • Without seeing your code I cannot help with your browser issue. My demo works in Chrome12 and Safari5 for me. It is likely you have other CSS that is affecting the layout. I would debug the `wordBottom > imageTops[imageIndex]` loop as that is the core logic. You need to debug what is happening when the code is looking to place the image back into the text. I can have a quick look at why the image in the second column is moving. – andyb Mar 29 '11 at 08:04
  • @andby.. I didnt changed your code much, I had increased the column height to 850(to match with iPad potraitview) and changed the image style property float:inherit;. So when i placed the image to the top of any column, I mean at the starting position of a column, the html breaks. – Krishna Mar 29 '11 at 12:11
  • Please look at the updated demo. It is working for me and please, please, please stop changing the requirements. I've been coding for a 500px height layout and suddenly you want it working on 850px. You have to be clear with what you are asking for. – andyb Mar 29 '11 at 12:14
  • @andyb. I am really sorry for the change in the height, but as you know for the iPad we have two views one is potrait(850px) and other is landscape which is(590px). So thats why i changed the height and tested and it is my requirement also. – Krishna Mar 29 '11 at 12:30
  • Minor edit to the "spanification" to cope with multiple whitespace. @Krishna please leave the CSS as `float:left`. It works. I just tried with `height:850px` and an `` at the top of a column. – andyb Mar 29 '11 at 12:30
  • @andby. Your code worked with safari 5, i was testing with safari 3 when i switched it to 5. It worked very well. I would also like to know one thing, is it possible that we can span the image over multiple columns. – Krishna Mar 30 '11 at 05:22
  • Multiple columns now? I doubt it will work since the CSS column-width needs to be set to make the columns possible. If `column-width:100px` and your image width is `200px` then it will be clipped. A `column-width` larger then the image width works nicely. Maybe you could investigate the spanning over multiple columns problem or ask in new different question. I think this question is already answered now. – andyb Mar 30 '11 at 11:30
  • @andby. Thanks for your efforts and I really appreciate it, without your help I couldn't have achieved this much. For image which spans over multiple columns, I put that Image outside of the column div(Top Position) and gives the width equal to the two columns, in this case image spans over two columns, but the third column starts from the same position where the first and second starts. Image spans only over first two columns, so the top portion of the third column remains blank. Is there any way that i can remove the blank space over the third column and starts third column from the top. – Krishna Mar 31 '11 at 05:56
0

If you add a style attribute to the div that contains the image to position it absolute, that might solve your problem.

HTML snippet:

<div>
    <div id="multicolumn4" >
        <span style='font-size:10px;'>
            <h1>The header of the columns</h1>
            <div class="imagediv">
                <img id="Image-Maps_5201006280459541" src="images/im1.png" usemap="#Image-Maps_5201006280459541" border="0" width="192" height="256" alt="" />
            </div>
            <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla at turpis eget nibh ultricies dignissim. Duis luctus euismod turpis. Mauris augue. Aliquam facilisis semper elit. Pellentesque semper hendrerit arcu. Phasellus eleifend commodo justo. Aliquam orci urna, imperdiet sit amet, posuere in, lobortis et, risus. Integer interdum nonummy erat. Nullam tellus. Sed accumsan. Vestibulum orci ipsum, eleifend vitae, mollis vel, mollis sed, purus. Suspendisse mollis elit eu magna. Morbi egestas. Nunc leo ipsum, blandit ac, viverra quis, porttitor quis, dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>
            <p>Nam ut sapien sed pede pulvin</p>
        </span>
    </div>
</div>

CSS:

.imagediv{float:left; margin-top: 30px; padding: 3px; }

Is this what you are looking for ?


The way to make text go around an image is by setting the style attribute "Float" on that image, or a surrounding element, like a div.

If you see that the image is changing position because the size of the text above the image increases, then that is just because that's how HTML works.

The position in the HTML is important to determine where to show your element on the rendered webpage.

With the information you gave, it is not clear enough how it should be. The code I provided lets the text go around the image, however the text ABOVE the div, or at least the image tag, will cause it to be pushed down.

There is, though, one possibility that would allow you to do such a thing, but it reaches beyond my skills, and that would be to remove the image with Javascript, and insert it back at a higher place in the HTML.

I hope I gave you enough information for you to think about a solution.

Steven Ryssaert
  • 1,989
  • 15
  • 25
  • thanks Uw Concept...but i had already tried with this, by applying this style will also make the image changes from its position when the text size is increased. The only css position property - 'fixed' will make it remain in the same position, but then the image is floating above the text. I need the image to be within the text and the text should flow around the image when the text size is increased. – Krishna Mar 23 '11 at 13:30
  • i placed it inside the master div. – Krishna Mar 23 '11 at 13:34
  • I have edited my HTML and CSS. Can you see if this is what you desire ? – Steven Ryssaert Mar 23 '11 at 13:39
  • I am sorry it didnt worked. Though the image didnt moved, the text goes down the image and the image floats above it. – Krishna Mar 23 '11 at 13:53
  • yes i added the css also as position absolute and float:left for the image div. – Krishna Mar 23 '11 at 13:59
  • There is no *position: absolute* in my css. – Steven Ryssaert Mar 23 '11 at 14:00
  • i tried both. with and without positin:abosulte. with position abosulte the image floats above the text and remained its initial position. without position:abosulte it places within the text, but displaces its position when the text size is increased. – Krishna Mar 23 '11 at 14:04
  • thanks Uw Concept for your valuable informations.. I will consider looking more into the javascript to keep the text move around the image. – Krishna Mar 23 '11 at 14:25
0

Updated Html for images which spans over multiple columns

 <html>
  <head>
    <title>Test</title>
    <g:javascript src="jquery.js"/>
    <script type="text/javascript">
           $(function(){
            var fontSize = 16;

            // cannot store img.position().top or .left here because it is
            // before the browser has re-flowed the columns, therefore the
            // positions will be incorrect
            var imageTops = new Array;
            var imageLefts = new Array;

            $('#fontUp').click(function() {
                reflow(1);
            });

            $('#fontDown').click(function() {
                reflow(-1);
            });

            function reflow(fontSizeStep) {
                storeImagePositions();
                var fontLimitReached = changeFont(fontSizeStep);
                if (!fontLimitReached) {
         //           moveImages();
                }
                return false;
            }

            function changeFont(step) {
                fontSize += step;

                var fontSizeLimitReached = true;

                if (fontSize > 30) {
                    fontSize = 30;
                } else if (fontSize < 16) {
                    fontSize = 16;
                } else {
                    fontSizeLimitReached = false;
                }

                if (!fontSizeLimitReached) {
            //      alert(fontSize)
                    $('p').css({fontSize: fontSize + 'px'});
                }

                return fontSizeLimitReached;
            }

            // initialize store of img top and left positions
            function storeImagePositions() {
                if (imageTops.length == 0) { // only do it once
                    $('img').each(function() {
                        var imgPosition = $(this).position();

                        imageTops.push(imgPosition.top);
                        imageLefts.push(imgPosition.left);
                    });
                }
            }

            function moveImages() {
                // bye bye images
                var images = $('img').detach();

                // clear any existing marginTop added on the images
                images.each(function() {
                    $(this).css('marginTop', 0);
                });


                // spanify paragraphs
                $('#column > p').each(function() {
                    $(this).html('<span>' + $(this).html().replace(/\s\s+/g).replace(/(\s)/g,'</span>$1<span>') + '</span>');
                });

                var imageIndex = 0;

                // iterate words, working out where we can move the img to in the flow and if
                // we find a match, increment the index so that as we continue the each()
                // the next image is evaluated for replacement
                $('#column > p span').each(function() {
                    var wordPosition = $(this).position();
                    var wordLeft = wordPosition.left;

                    if (wordLeft >= imageLefts[imageIndex]) {
                        var wordBottom = wordPosition.top + $(this).height();

                        if (wordBottom > imageTops[imageIndex]) {
                            $(this).before(images[imageIndex]); // move img before this word
                            var newImgTop = $(images[imageIndex]).position().top;
                            $(images[imageIndex]).css({marginTop: imageTops[imageIndex] - newImgTop + 'px'});
                            imageIndex++; // increment index so remainder spans are being evaluated against the next image
                        }
                    }
                });

                // reverse the "spanification"
                $('#column > p').each(function() {
                    $(this).html($(this).html().replace(/<\\?span>/g, '').trim());
                });
            }
        });
    //]]>
    </script>
    <style type="text/css">
      div#column {
        margin-left:20px;
        -moz-column-width: 250px;
        -moz-column-gap: 20px;
        -webkit-column-width: 250px;
        -webkit-column-gap: 20px;
        height: 850px;
      }

      p {
        margin:0;
        clear:left;
        font-size:16px;
        text-align:justify;
      }

      img {
        float:left;
        margin-top: 2px;
        margin-right: 10px;
        position:fixed;
      }
    </style>
  </head>
  <body>
    <div><a href="#" id="fontUp" style="margin-right:10px">Font +</a><a href="#" id="fontDown">Font -</a></div>
    <div><img src="${createLinkTo(dir:'images',file:'Winter.jpg')}" height="250" width="660" id="image" title="yoda" alt="yoda"/></div>
          <div id="column" style="margin-top: 255px;">
            <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            <p>The change of name from  LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion,  giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language. It has also been claimed that the language's name is the result of a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>
            <p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>
            <p>Java EE includes several API specifications, such as JDBC, RMI, e-mail, JMS, web services, XML, etc., and defines how to coordinate them. Java EE also features some specifications unique to Java EE for components. These include Enterprise JavaBeans, Connectors, servlets, portlets (following the Java Portlet specification), JavaServer Pages and several web service technologies. This allows developers to create enterprise applications that are portable and scalable, and that integrate with legacy technologies.  A Java EE application server can handle transactions, security, scalability, concurrency and management of the components that are deployed to it, in order to enable developers to concentrate more on the business logic of the components rather than on infrastructure and integration tasks.</p>
            <p>Java (Indonesian: Jawa) is an island of Indonesia. With a population of 136 million, it is the world's most populous island, and one of the most densely populated regions in the world. It is home to 60% of Indonesia's population. The Indonesian capital city, Jakarta, is in west Java.  Much of Indonesian history took place on Java; it was the centre of powerful Hindu-Buddhist empires, Islamic sultanates, the core of the colonial Dutch East Indies, and was at the centre of Indonesia's campaign for independence. The island dominates Indonesian social, political and economic life.</p>
            <p>Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk. It can be used as a scripting language for the Java Platform.
              Groovy uses a Java-like bracket syntax. It is dynamically compiled to Java Virtual Machine (JVM) bytecode and interoperates with other Java code and libraries. Most Java code is also syntactically valid Groovy.</p>
            <p>Scala runs on the Java platform (Java Virtual Machine) and is compatible with existing Java programs. It also runs on Android smartphones. An alternative implementation exists for the .NET platform, but it has not been kept up to date.
              Scala has the same compilation model as Java and C# (separate compilation, dynamic class loading), so Scala code can call Java libraries (or .NET libraries in the .NET implementation).Scala's operational characteristics are the same as Java's. The Scala compiler generates byte code that is nearly identical to that generated by the Java compiler. In fact, Scala code can be decompiled to readable Java code, with the exception of certain constructor operations. To the JVM, Scala code and Java code are indistinguishable.</p>
          </div>
  </body>
</html>
Krishna
  • 361
  • 2
  • 9
  • 24
  • Could you please post this as a new question, rather than an answer to the question above. It really is a separate question. Also, I'm not sure if there is a _comment limit_ on a question but the comments section on my answer is getting very long and is in danger of being too long for anyone to bother reading. – andyb Mar 31 '11 at 06:52