简体   繁体   中英

Vertically centering a <div> element

I've been attempting to center a sidebar vertically, I centered it horizontally however. I'm aware of the display:table; but that's not what I want to do, because I'm going to be putting the main content area right next to the sidebar. Here's the code and style:

<div class="sidebar">
    <ul>
        <li>Homepage</li>
        <li>blah</li>
        <li>blah</li>
        <li>blah</li>
        <li>blah</li>
        <li>blah</li>
        <li>blah</li>
        <li>blah</li>
    </ul>   
</div>  

CSS:

div.sidebar{
    background-color:       #DEFFFF;
    width:                  156px;
    height:                 385px;
}

div.sidebar a{
    color:                  black;
    display:                block;
}

div.sidebar ul li{
    margin-left:            -33px;
    list-style-type:        none;
    width:                  140px;
    height:                 25px;
    border-right:           1px solid black;
    border-top:             1px solid black;
    border-left:            1px solid black;
    background-color:       #BCA264;
    font-family:            bold;
}

CSS3 solution: http://jsfiddle.net/RazvanGirmacea/HDyuX/

display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-pack: center;

display: -moz-box;
-moz-box-orient: vertical;
-moz-box-pack: center;

display: box;
box-orient: vertical;
box-pack: center;
<div class="parentPanel">
  <div class="content">
    <img src="http://placehold.it/400x500">
  </div>
  <div class="sidebar">
    <ul>
      <li>Homepage</li>
      <li>blah</li>
      <li>blah</li>
      <li>blah</li>
      <li>blah</li>
      <li>blah</li>
      <li>blah</li>
      <li>blah</li>
    </ul>
  </div>
</div>

And use the following CSS

.parentPanel {
    border: 1px solid blue;
}
.content {
    border: 1px solid blue;
    display: inline-block;
    vertical-align: middle;
}
.content img {
    display: block;
}
.sidebar {
    border: 1px solid blue;
    display: inline-block;
    vertical-align: middle;
}

You can re-size the content area as you see fit, and style the side bar and links accordingly.

For reference: http://jsfiddle.net/audetwebdesign/KUFRK/

Note
I assumed that the content area is taller than the navigation bar list.

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