views:

438

answers:

6

I have a div that contains an image and a p tag (seen below). I want to align the image in the middle of the div vertically depending on how many lines the paragraph is. Vertical-align doesn't work. I am using JavaScript right now to figure out how much to add to margin-top, but would rather use CSS. Any ideas?

<div>
    <img>
    <p>Multi-line</p>
</div>
A: 

Add

div img {
    float: left;
}
Daniel A. White
Already is floated, maybe should have added that in.I have the image floating left and the p with a margin-left.
jakeprzespo
Will this not just keep in the top left?
dbrien
A: 

Is it kind of a two column job? (image to the left, text to the right)

If so, you could surely just stick each element in its own div...

<div>
    <div style="width:100; float:left"><img /></div>
    <div style="width:100; float:left"><p>multiline</p></div>
</div>

Think that would do what you're after

Paul
A: 

Give the image display: block, float: left and vertical-align: middle. Or, give it a line height equal to that of the containing element.

+1  A: 

Try setting the line-height attribute of the p element to the height of the image, eg:

div p {
  line-height: 18px;
}

Edit: Just realised I misread the question and missed the fact the p would be multi-line. One option to try is removing the img element altogether and setting it as the background-image of the p instead, with a background-position of left, center. Something like:

div p {
  background: transparent url(path/to/img) no-repeat left center;
  padding-left:30px; /* Set based on width of image */
}
Luke Bennett
This is a good solution. However in my example, the image will change and will not be a set image.
jakeprzespo
You could always set the background-image attribute as an inline style:<p style="background-image:url(dynamically/generated/path/to/img)">Multi-line</p>
Luke Bennett
I could also just set the <p> to a specific class dynamically that will have the different images.
jakeprzespo
+1  A: 

the CSS vertical-align attributes only works on table cells and inline elements. Since the paragraph tag specifies a block element by default, it does nothing. In order for your text to be aligned as you describe, you either have to separate your div into two containers or use a table. Here's a good page to help you understand a little bit better: Understanding vertical-align

snicker
A: 

Maybe the solution at Jak psát web will help.

Ewan Todd