Vertical centering of div without Javascript when div's height isn't fixed

寵の児 提交于 2019-12-13 02:09:17

问题


I would like to vertical center a div without JavaScript when its height isn't fixed.

I found here one idea.

I wonder if there are other solutions to this problem.


回答1:


This works:

Here's link: http://jsbin.com/uvodop/2/edit

See how it's vertically aligned within the box. Height as well isn't fixed.

Hope it answers your question.

<html>
<head>
    <title>HTML Div vertical align using CSS</title>
    <style type="text/css">
        .outerDiv {
            border: solid 1px #000000;
            width: 300px;
            padding: 5px 2px 5px 2px;
        }

        .innerDiv {
            width: 95%;
            margin: 0px auto;
            padding: 40px 0px 40px 5px;
            border: solid 1px #000000;
        }
    </style>
</head>
<body>
    <div class="outerDiv">
        <div class="innerDiv">
            This text is placed inside the next HTML div tag.<br />
            CSS style is used to vertical align the nested div and text.
        </div>
    </div>
</body>
</html>



回答2:


Though this is an old thread, I think this answer might help someone. If the version of IE is flexible to at least IE > 8, then you can use display:table-cell and use the default vertical-align feature.

In the code below, the div.hover which is the div that is going to be vertically aligned middle is not assigned any height however the parent(s) are assigned 100% height to fill the screen.

Check this out

.outer {
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background-color: #aaa;
  display: table;
}
.inner {
  display: table-row;
  border: 1px solid #0f0;
  height: 100%;
}
.center {
  display: table-cell;
  border: 1px solid #00f;
  vertical-align: middle;
  height: 100%;
}
.hover {
  width:100px;
  border: 1px solid #f00;
  margin-left: auto;
  margin-right: auto;
}
<div class="outer">
  <div class="inner">
    <div class="center">
      <div class="hover">
        I am a random text to give the div some height
      </div>
    </div>
  </div>
</div>


来源:https://stackoverflow.com/questions/8997500/vertical-centering-of-div-without-javascript-when-divs-height-isnt-fixed

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