Jacob
Jacob

Reputation: 5

How do I center text next to a floating image using css?

<html>
    <head>
        <style type="text/css">
            img{
                float: left;
                }
        </style>
    </head>
    <body>
        <img id="img" src="imgsource.jpg">
        <h2> Text that should be next to the image. </h2>
        <p> Text that should be below the image and heading. </p>
    </body>
</html>

The problem I'm having is that the text next to the image isn't centered and the next paragraph also goes next to the image when I would like it below the image and heading.

Upvotes: 0

Views: 2946

Answers (2)

Praxis Ashelin
Praxis Ashelin

Reputation: 5217

In order to do this, you should change your HTML structure a bit first:

<img id="img" src="https://placekitten.com/g/200/300">
<div id="text">
    <h2> Text that should be next to the image. </h2>
</div>

<div class="clear"></div>
<p> Text that should be below the image and heading. </p>

Then use floats on the correct elements to position them next to eachother:

img, #text{
    float: left;
}

Using display: table-cell and vertical align you can vertically center your text next to the image. Note: you must know your image height for this.

#text h2{
    vertical-align: middle;
    height: 300px;
    display: table-cell;
    padding-left: 10px;
}

Finally, don't forget to clear your floats so the rest of your text appears below the image.

.clear{
    clear: both;
}

JSFiddle demo

Upvotes: 0

Timmerz
Timmerz

Reputation: 6199

http://jsfiddle.net/dxbbog2k/

img {
    vertical-align: middle;
    width: 300px
}

h2{
    display: inline;
}

p{
    clear:both;
    display: block;
}
<img id="img" src="http://dreamatico.com/data_images/kitten/kitten-3.jpg">
<h2> Text that should be next to the image. </h2>

<p>Text that should be below the image and heading.</p>

Upvotes: 1

Related Questions