Center block vertically and horizontally with dynamic width and height

泄露秘密 提交于 2019-12-18 07:30:10

问题


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>

回答1:


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/



来源:https://stackoverflow.com/questions/8328314/center-block-vertically-and-horizontally-with-dynamic-width-and-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!