简体   繁体   中英

Vertically align image with caption in div

I am trying this solution (first answer) to vertically align an image over a div that has the following additional css properties so it takes the whole space:

    position: absolute; 
    top: 0px; 
    bottom: 0px;
    left: 0px;
    right:0px;

The problem is, even with the fiddle referenced in the original question ( here ), if you add an additional span with a text, separated by a <br/> , this span shows outside of the containing div.

I want to align both the image and caption inside the div.

Any ideas?

HTML:

<html>
<head>
<title>Splash screen</title>
<style>
.frame {
    position: absolute; 
    top: 0px; 
    bottom: 0px;
    left: 0px;
    right:0px;
        text-align: center; 
}
.helper {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
img {
    vertical-align: middle;
    max-height: 25px;
    max-width: 160px;
}
</style>
</head>
<body>
<div class="frame">
    <span class="helper"></span>
      <img class="center" src="img/splash/splash.png" />
      <br />
      HELLO WORLD
</div>
</body>

To adjust with <br /> , you'll have to change height to min-height

updated fiddle

and this is your css :

frame {
    min-height: 25px;      /* equals max image height */
    width: 160px;
    border: 1px solid red;
    text-align: center; margin: 1em 0;
}

Also, in your example fiddle, class is assigned wrong way :

<div class=frame>

this is wrong

<div class="frame">
      /*___^_____^ see the quotes */

EDIT

In you case...keep span inline and set position:relative

span.helper {
    display: inline;
    height: 100%;
    vertical-align: middle;
    position: relative;
}

wroking demo

EDIT 2

Use display:table to achieve your purpose rather than position .

Note CSS table is IE8= compatible!!

working fiddle

html, body {
    width:100%;
    height:100%;
    margin:0;
    padding:0;
}
.table {
    display:table;
    width:100%;
    height:100%;
    margin:0;
    padding:0;
}
.frame {
    display:table-cell;
    vertical-align:middle;
    border: 1px solid red;
    text-align: center;
}
.helper {
    display: inline;
    height: 100%;
    vertical-align: middle;
    position: relative;
}
img {
    background: #3A6F9A;
    vertical-align: middle;
    max-height: 25px;
    max-width: 160px;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM