简体   繁体   中英

How can I center a div inside a div?

I'm trying to create a contact list but can't wrap my head around it. I want to vertically center the detailspanel:

.contactpanel .icon
{
    background: url('http://www.alter-net.info/Person.png');
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: 14px 14px;
    position: absolute;
    left: 0;
    width: 60px;
    height: 60px;
}

.contactpanel .detailspanel
{
    margin-left: 65px;
}

It's on JSFiddle:

http://jsfiddle.net/hu6wq7km/

I want the details (name and email) to be centered vertically inside the panel, how can I accomplish that?

If the height is unknown you could use the "table trick" to vertically center your content.

Link to JSbin: http://jsfiddle.net/9xqdtbqu/

CSS:

.contactpanel
{
    display:table;
}

.contactpanel .icon
{
   display: table-cell;
   vertical-align: middle;      

}

.contactpanel .detailspanel
{
   display: table-cell;
   vertical-align: middle;    
} 

Using padding top and bottom you can do this, add padding to detailpanel

update your css for class detailspanel

.contactpanel .detailspanel
{
    margin-left: 65px;
    padding: 12px 0;
}

http://jsfiddle.net/hu6wq7km/5/

Or as an alternative you could try this:

.contactpanel .detailspanel {
    bottom: 0;
    height: 40px;
    margin: auto 0 auto 65px;
    position: absolute;
    top: 0;
}

Looking at the height of the contactpanel which is 60px and you have a div with id detailspanel . Simple padding will adjust the detailspanel in center .

try with padding : 10px which will adjust the detailspanel to center.

To adjust with complete control of the elements on the page. set the individual div's of name and email to a height of 15px without any padding and margin: 10px , this will do the trick. Since the margin-bottom and margin-top of name and email div will collapse.

Add position absolute for the div.detailspanel like below:

.contactpanel .detailspanel
{
    margin-left: 74px;
    position: absolute;
    margin-top: 11px;
}

For your reference check this fiddle: http://jsfiddle.net/hu6wq7km/9/

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