简体   繁体   中英

Vertically aligning elements with CSS

I have an element that's 60px tall that has other elements like an image and a couple of spans inside of it and I'm having trouble getting them to align vertically inside the 60px high element. Here's the mockup and CSS:

<div class="member">
    <img src="images/pic.png" alt="John Smiths's Profile Picture" class="pic">
    <span class="name"><a href="">John Smith</a></span>
    <span class="skills">PHP, MySQL, Javascript, C#, Java</span>
</div>

#sidebar .member {
    height: 60px;
    margin-bottom: 10px;
    vertical-align: center;
}

#sidebar .member .name {
    font-size: 15px;
    font-weight: bold;
}

#sidebar .member .pic {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    float: left;
    margin-right: 10px;
}

#sidebar .member .skills {
    display: block;
    font-size: 12px;
    overflow: hidden;
}

I've put it up on jsfiddle: http://jsfiddle.net/CYFyx/2/

As you can see, the elements within the .member element push to the top. I need them vertically aligned like so:

在此输入图像描述

Already tried vertical-align: middle; but with no luck.

You can use vertical-align: middle in td table layout only. So you have to add a div around the spans

<div class="cell">
    <span class="name"><a href="">John Smith</a></span>
    <span class="skills">PHP, MySQL, Javascript, C#, Java</span>
</div>   

with this properties

#sidebar .member .cell {
    display: table-cell;
    vertical-align: middle;
    height: 50px;
}

You can test it here: http://jsfiddle.net/Tn2RU/

Try putting them all in a div that you can vertically align using

position:relative; 
margin-top: auto; 
margin-bottom: auto; 
height: XXpx;

You need to set the width of a parent element and width of your children so they must go into next line.

The other posibility would be to set your parent element to position:relative and then use position:absolute on all children and simply, precisely position them with top:20px; , then next one top:40px; etc etc.

With this second solution you can get exact pixel positioning of all children elements.

That shall positively give you best results.

You could also put them into a div and add padding to the top.

HTML

<div id="block">
        <span class="name"><a href="">John Smith</a></span>
        <span class="skills">PHP, MySQL, Javascript, C#, Java</span>
</div>

CSS

#block {
 padding-top:5px;  
}

jsFiddle

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