Daft
Daft

Reputation: 10964

Positioning text with the :after pseudo selector

I have this:

    div#myImg{
        background: url('myimage.png') left top no-repeat;
    }

    div#myImg:after{
        content: 'TEXT UNDER IMAGE';
        margin:0 auto;
        vertical-align:text-bottom;
        font-size: 14px;
    }           

    .dm_lp_imgs{
        width: 100px;
        float:left;
        height: 115px;
        margin-right: 15px;
    } 


    <div id="myImg" class="lp_imgs"></div>

I know you can add text with the :after pseudo selector, but I want to position that text, centered, just below my image. Can I do that with the :after pseudo selector?

At the moment, the text seems stuck to the top of the div#myImg DIV.

UPDATE:

display:block

Doesn't do the trick...

Upvotes: 0

Views: 121

Answers (3)

fnostro
fnostro

Reputation: 4591

I don't know your requirements but if you're coding for modern browsers/html5 you should look into the <figure> and <figcaption> html tags

For your consideration: FIDDLE

Markup:

<figure id="myFigure">
    <div id="myImg" class="dm_lp_imgs"></div>
    <figcaption>text under image</figcaption>
</figure>

CSS

.dm_lp_imgs {
    width: 100px;
    height: 115px;
}

#myFigure {
    float:left;
    margin-right: 15px;
    width: 100px;
}

#myImg { background: url('myimage.png') left top no-repeat; }

#myImg + figcaption {
    /* Style caption here */
    text-align:center;
    text-transform:capitalize;
}

Upvotes: 2

Joseph Marikle
Joseph Marikle

Reputation: 78520

Usually I use CSS position to do that sort of thing. Make the parent position:relative, add position:absolute to the ::after element, and give it a top:100%

http://jsfiddle.net/s22Af/

div#myImg:after{
    content: 'TEXT UNDER IMAGE';
    margin:0 auto;
    vertical-align:text-bottom;
    font-size: 14px;

    position:absolute;
    top: 100%;
    text-align: center;
}           

.dm_lp_imgs{
    width: 100px;
    float:left;
    height: 115px;
    margin-right: 15px;

    position: relative;
} 

Upvotes: 4

edcs
edcs

Reputation: 3879

You can position pseudo elements absolutely relative to the parent. Add position: relative to the div and position: absolute to the :after CSS, then position using usual methods. I've done a quick fiddle of it here: http://jsfiddle.net/5s3Fr/

Upvotes: 3

Related Questions