简体   繁体   中英

Center each text horizontally and vertically to its image

I am trying to figure out how center each text horizontally and vertically to its corresponding image with what I have so far.

Does anyone have any suggestions?


Here is what I have so far:

<div class="content">CYREX
    <input type="image" src="http://img42.com/qXPbx+" class="thumbnils" />
</div>
<div class="content">HITMAN
    <input type="image" src="http://img42.com/qXPbx+" class="thumbnils" />
</div>

css:

.content{
    width: 100px;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    padding: 0;
    position: relative;
}

.thumbnils{width: 70%;}

FIDDLE

If you need to keep your HTML markup, you can use like this:

 .content{ width: 100px; display: block; float: left; text-align: center; padding: 0; position: relative; } .content span { position: absolute; left: 0; top: 50%; margin-top: -10px; width: 100%; } .thumbnils{ width: 70%; } 
 <div class="content"> <span>CYREX</span> <input type="image" src="http://img42.com/qXPbx+" class="thumbnils" /> </div> <div class="content"> <span>HITMAN</span> <input type="image" src="http://img42.com/qXPbx+" class="thumbnils" /> </div> 

But if you don't need to bother about IE8< compatibility and those are just images, you could use like this:

 .content { width: 100px; display: block; float:left; text-align: center; padding: 0; position: relative; background: url("http://img42.com/qXPbx+") no-repeat center center; background-size:contain; height: 80px; line-height: 80px; } 
 <div class="content"> <span>CYREX</span> </div> <div class="content"> <span>HITMAN</span> </div> 

But be aware of the background-size browser compatibility .

if you want to keep your HTML and you don't mind using css3 you may use this CSS:

.content{
    width: 100px;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    padding: 0;
    position: relative;
}
.content span {
    position:absolute;
    top:50%;
    left:50%;
    -moz-transform: translateY(-50%) translateX-50%);
    -webkit-transform: translateY(-50%) translateX(-50%);
    -o-transform: translateY(-50%) translateX(-50%);
    -ms-transform: translateY(-50%) translateX(-50%);
    transform: translateY(-50%) translateX(-50%);
}
.thumbnils{
    width: 70%; 
}

Taking into account I have just wrapped your text inside a span tag so I could call it with css.

FIDDLE

put the text in spans and add this to the css

span 
{
    font-size: 20px;
    line-height: 20px;
    position: absolute; 
    top: calc(50% - 10px); /* half of font size */
    left: 0px;
    text-align: center;
    width: 100%;
    z-index: 999;
}

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