Floating images - A Smarter Way To Learn HTML & CSS (2015)

A Smarter Way To Learn HTML & CSS(2015)

28
Floating images

Would you like to wrap some text around an image? Here’s how.

img.wrap-around-the-right-side {
float: left;
}

Now any text that comes after the image in your HTML code will wrap around the image, on the right. If the text is too long to fit completely next to the image, it’ll continue at full width under the image.

Note that there’s no display: block here. The image will share its horizontal space if there’s room.

If you want text to wrap around the left side of the image, you’d write:

img.r-float {
float: right;
}

When you do this, you’ll notice that the browser jams the text up against the image, leaving no breathing room. You can correct this by adding some margin to the image. In the following code, whitespace is added between the image and the text on its right. Whitespace is also added below the image, to give breathing room between the image and any text that flows beneath the image.

img.wrap-around-the-right-side {
float: left;
margin: 0 .75em .5em 0;
}

There’s one unintended consequence you need to avoid. Let’s say you have a short paragraph wrapping around the left side of an image. The paragraph is so short that it doesn’t fill all the space to the left of the image. If you add another paragraph under the short paragraph, it will wrap. If you don’t want this, you need to tell the browser to clear the float after the first paragraph. To do this, you create a class.

p.no-wrap {
clear: both;
}

By telling the browser to clear both, you’re saying, “Don’t wrap anything from here on.” Here’s the HTML.

<img class="wrap-around-the-right-side" src="images/founder.jpg" alt="Our founder" width="55" height="85"> <p>This is our founder, Bradley B. Bradley, who envisioned a Brad’s Breadsticks on every corner.</p><p class="no-wrap">Wherever you go, you’ll find a Brad’s Breadsticks nearby, with breadsticks in 43 delicious flavors.</p>

1. In your CSS file code a class of images that floats and creates some space between it and the text that wraps around it.

2. Create a class of paragraphs that clears the wrap.

3. In your HTML file copy the image tag for the smaller version of the loris. Replace the class name with the class that floats.

4. Code a paragraph that will wrap around the image.

5. Code a paragraph that clears the wrap.

6. Save the files and display the page.

Sample CSS code is at:
http://asmarterwaytolearn.com/htmlcss/practice-28-1.html.

Sample HTML code is at:
http://asmarterwaytolearn.com/htmlcss/practice-28-2.html.

Find the interactive coding exercises for this chapter at:
http://www.ASmarterWayToLearn.com/htmlcss/28.html