如何使自定义对话框中的文本垂直居中

时间:2015-04-25 04:55:41

标签: html css html5 css3

我需要你的帮助,

我如何修改下面的HTML或CSS标记,使我的自定义对话框中的文本在白色空间中垂直居中。以下是问题的快照: enter image description here

和预期结果: enter image description here

这是CSS:

#wrapper {
    height: 100px;
    width: 500px;
    bottom: 50%;
    right: 50%;
    position: absolute;
}

#container {
    background: #FFF;
    left: 50%;
    padding: 10px;
    top: 50%;
    margin: 0;
    padding: 0;
    height: 100%;
    border: 2px solid rgb(100,139,170);
    height: 100%;
    position: relative;
}
.topbar {
    cursor: pointer;
    color: white;
    background: rgb(100,139,170);
    padding: 4px;
    font-weight: bold;
}

#Text {
  width: 100%;
  height: 100%;
  text-align: center;
}

这是HTML:

<div id="wrapper">

    <div id="container">

        <div style="float:left;" class="topbar">Custom Dialog Box</div><div class="topbar" style="text-align: right;">Close</div>

        <div id="Text">This is some sample text that will appear here</div>

    </div>

</div>

小提琴是:https://jsfiddle.net/vc5xL1vy/

2 个答案:

答案 0 :(得分:0)

有多种方法可以做到这一点,但它们都要求你为某些东西设置一个像素值。填充,线高等... 您可以将容器显示设置为表格单元格,使其像表格元素一样,然后设置文本容器的宽度和高度,以便元素知道中间位置。使用%永远不会用于垂直对齐。 CSS中的痛苦。

#Text {
  width: 500px;
  height: 75px;
  text-align: center;
  display: table-cell;
  vertical-align: middle;
}

https://jsfiddle.net/bgbfpbta/

答案 1 :(得分:0)

您需要将容器设置为display: table;并将其所有子容器设置为display: table-cell,但将表头设置为display: table-caption。我已经对你的标题做了一些其他修改到一个div包装器。 JSFiddle:https://jsfiddle.net/1s45cdvs/1/

CSS

#wrapper {
    height: 100px;
    width: 500px;
    bottom: 50%;
    right: 50%;
    position: absolute;
}

#container {
    background: #FFF;
    left: 50%;
    padding: 10px;
    top: 50%;
    margin: 0;
    padding: 0;
    height: 100%;
    border: 2px solid rgb(100,139,170);
    height: 100%;
    position: relative;
    display:table;
}
.topbar {
    cursor: pointer;
    color: white;
    background: rgb(100,139,170);
    padding: 4px;
    font-weight: bold;
    display: table-caption;
}

#Text {
  text-align: center;
    display: table-cell;
    vertical-align: middle;
}

HTML

<div id="wrapper">

    <div id="container">

        <div class="topbar">
            <div style="float:left;" >Custom Dialog Box</div><div style="text-align: right;">Close</div>
        </div>

        <div id="Text">This is some sample text that will appear here</div>

    </div>

</div>