Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - Center block vertically and horizontally with dynamic width and height

I need to center an element both vertically and horizontally and the element can't have any fixed dimensions. The contents of the element must not be affected...meaning some elements will be text-align left, others center, they may be images, etc etc.

Here's where I'm at currently: http://jsfiddle.net/Shpigford/BUbmz/

The width and height of the blue block changes dynamically based on the content and centers horizontally, which works fine.

But what I now need to do is center the blue block vertically.

The blue block can't have any fixed dimensions, though the red block can.

Here's my CSS:

section {
  width: 500px;
  height: 300px;
  background: red;
}
.options {
  display:table;
  margin: 0 auto;
  background: blue;
}
h2 {
  text-align: center;
  margin: 0;
  padding: 0;
}
ul {
  margin: 0;
  padding: 0;
  text-align: center;
}
li {
  text-align: left;
}

And HTML:

<section>
  <div class="options">
    <h2>My question</h2>
    <ul>
      <li>Ligula Quam</li>
      <li>Condimentum Nullam Mollis</li>
      <li>Aenean</li>
      <li>Commodo Dolor Nibh Ligula Vulputate</li>
    </ul>
  </div>
</section>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here's a solution for centering DIVs vertically, with fallbacks for various browsers, including older IE versions.

http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

[edit]

Translated, your fiddle becomes like this:

http://jsfiddle.net/GolezTrol/BUbmz/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...