我有一个包含图像和ap标签的div(见下文).我想根据段落的行数垂直对齐div中间的图像.垂直对齐不起作用.我现在正在使用JavaScript来计算添加到margin-top的数量,但宁可使用CSS.有任何想法吗?
Multi-line
0b10011.. 60
这是纯CSS,垂直对齐图像,如果图像比包含框更高(或更宽),也会调整图像大小.因此,盒子和图像都可以是任何尺寸而不会破坏垂直对齐.此外,您可能希望为标记添加左边距,以防止它们被图像隐藏.
/* Positioning */
.absoluteCenterWrapper {
position: relative; /* Contains the image in the div */
}
.absoluteCenter { /* Aligns image vertically */
margin: auto;
position: absolute;
top: 0;
bottom: 0;
}
.absoluteCenterWrapper p { /* Pushes to edge of image */
margin-left: 101px; /* Width of image */
}
.absoluteCenter { /* Specifies width of image to avoid overlap if image changes */
width: 101px; /* Width of image */
}
/* Sizing - resizes down to avoid cutting off */
.absoluteCenter {
max-height: 100%;
max-width: 100%;
}
/* Making it "pretty" */
.absoluteCenterWrapper { margin: 1em; padding: 0.001em; /* <- Hack to contain margins */ outline: 1px solid red; }
.absoluteCenterWrapper p { margin-top: 1em; margin-bottom: 1em; padding-left: 1em;}
Paragraph goes here.
Paragraph goes here.
Paragraph goes here.
Paragraph goes here.
Paragraph goes here.
这是纯CSS,垂直对齐图像,如果图像比包含框更高(或更宽),也会调整图像大小.因此,盒子和图像都可以是任何尺寸而不会破坏垂直对齐.此外,您可能希望为标记添加左边距,以防止它们被图像隐藏.
/* Positioning */
.absoluteCenterWrapper {
position: relative; /* Contains the image in the div */
}
.absoluteCenter { /* Aligns image vertically */
margin: auto;
position: absolute;
top: 0;
bottom: 0;
}
.absoluteCenterWrapper p { /* Pushes to edge of image */
margin-left: 101px; /* Width of image */
}
.absoluteCenter { /* Specifies width of image to avoid overlap if image changes */
width: 101px; /* Width of image */
}
/* Sizing - resizes down to avoid cutting off */
.absoluteCenter {
max-height: 100%;
max-width: 100%;
}
/* Making it "pretty" */
.absoluteCenterWrapper { margin: 1em; padding: 0.001em; /* <- Hack to contain margins */ outline: 1px solid red; }
.absoluteCenterWrapper p { margin-top: 1em; margin-bottom: 1em; padding-left: 1em;}
Paragraph goes here.
Paragraph goes here.
Paragraph goes here.
Paragraph goes here.
Paragraph goes here.
尝试将元素的line-height
属性设置为p
图像的高度,例如:
div p { line-height: 18px; }
编辑:刚刚意识到我误解了这个问题并错过了p
多线的事实.尝试一种选择是去除img
共元素,并将其设置为background-image
的p
不是,用background-position
的left, center
.就像是:
div p { background: transparent url(path/to/img) no-repeat left center; padding-left:30px; /* Set based on width of image */ }