Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

html - CSS vertically align floating divs

I have a div (#wrapper) containing 2 divs standing side by side.

I would like the right-div to be vertically aligned. I tried vertical-align:middle on my main wrapper but it is not working. It is driving me crazy!

Hope someone can help.

http://cssdesk.com/LWFhW

HTML:

<div id="wrapper">
  <div id="left-div">
    <ul>
      <li>One</li>
      <li>Two</li>
    </ul>
  </div>  
  <div id="right-div">
    Here some text...
  </div>
</div>

CSS:

#wrapper{
  width:400px;
  float:left;
  height:auto;
  border:1px solid purple;}

#left-div{
  width:40px;
  border:1px solid blue;
  float:left;}

#right-div{
  width:350px;
  border:1px solid red;
  float:left;}

ul{
  list-style-type: none;
  padding:0;
  margin:0;}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have no luck with floated elements. They don't obey vertical-align,

you need, display:inline-block instead:

http://cssdesk.com/2VMg8

BEWARE


Be careful with display: inline-block; as it interpretes the white-space between the elements as real white-space. It does not ignores it like display: block does.

I recommend this:

Set the font-size of the containing element to 0 (zero) and reset the font-size to your needed value in the elements like so

ul {
    margin: 0;
    padding: 0;
    list-style: none;
    font-size: 0;
}
ul > li {
    font-size: 12px;
}

See a demonstration here: http://codepen.io/HerrSerker/pen/mslay


CSS

#wrapper{
  width:400px;
  height:auto;
  border:1px solid green;
  vertical-align: middle;
  font-size: 0;
}

#left-div{
  width:40px;
  border:1px solid blue;
  display: inline-block;
  font-size: initial;
  /* IE 7 hack */
  *zoom:1;
  *display: inline;
  vertical-align: middle;
}

#right-div{
  width:336px;
  border:1px solid red;
  display: inline-block;  
  font-size: initial;
  /* IE 7 hack */
  *zoom:1;
  *display: inline;
  vertical-align: middle;
}
  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...