将代码块对齐到给定区域的中心

时间:2014-04-23 12:57:14

标签: html css

这是我的代码:http://jsfiddle.net/spadez/QJDjh/2/

HTML

<div id="header" class="fullheight center">
    <div id="nav">
        <ul>
            <li>Home</li>
            <li>Price</li>
        </ul>
    </div> <span>Big message</span>
 <span>Smaller message</span>
 <a href="#" id="sign_up">Sign up free</a>
 <span>Sub notes</span>
down arrow</div>
<div id="content">Hello</div>

CSS

* {
    padding: 0px;
    margin: 0px;
}
html, body {
    height:100%;
}
#header {
    background-color: #3B2F63;
    background-image: -webkit-radial-gradient(50% top, rgba(84, 90, 182, 0.6) 0%, rgba(84, 90, 182, 0) 75%), -webkit-radial-gradient(right top, #794aa2 0%, rgba(121, 74, 162, 0) 57%);
    background-repeat: no-repeat;
    background-size: 100% 1000px;
    color: #c7c0de;
    margin: 0;
    padding: 0;
}
#header {
}
#content {
    background-color: white;
}
.fullheight {
    height: 100%;
}
.center {
    text-algin: center;
}
span {
    display: block;
}
#sign_up {
    padding: 10px;
    background: white;
    border-radius: 3px;
}

我试图将以下区块放在verticallyhorizontally的中心位于紫色区域的中心位置:

<span>Big message</span>
<span>Smaller message</span>
<a href="#" id="sign_up">Sign up free</a>
<span>Sub notes</span>

我想在不破坏布局的情况下这样做。我是否必须将此块放在一个新的div中,并设置相等的边距?

2 个答案:

答案 0 :(得分:1)

您可以使用display:table属性来实现您的目标:

<强> HTML

<div id="header" class="table">
    <div class="row top">
        <div class="cell">
            <ul>
                <li>Home</li>
                <li>Price</li>
            </ul>
        </div>
    </div>
    <div class="row middle">
        <div class="cell">
            <span>Big message</span>
            <span>Smaller message</span>
            <a href="#" id="sign_up">Sign up free</a>
            <span>Sub notes</span>
        </div>
    </div>
    <div class="row bottom">
        <div class="cell">
            down arrow
        </div>
    </div>
</div>

<div id="content">
    Hello           
</div>

<强> CSS

.table { height: 100%; display:table; width:100%; }
.row { display:table-row; }
.cell { display:table-cell; text-align:center; vertical-align:top; }
.middle .cell { vertical-align:middle; height:100%;}

Example

答案 1 :(得分:0)

你需要jquery帮助来做到这一点: 把它包装成这样的div:

<div class="className">
<span>Big message</span>
<span>Smaller message</span>
<a href="#" id="sign_up">Sign up free</a>
<span>Sub notes</span>
down arrow
</div>

然后使用这样的脚本:

$(document).ready(function(){

 $(window).resize(function(){

  $('.className').css({
   position:'absolute',
   left: ($(window).width() 
     - $('.className').outerWidth())/2,
   top: ($(window).height() 
     - $('.className').outerHeight())/2
  });

 });

 // To initially run the function:
 $(window).resize();

});

Source。输出:http://jsfiddle.net/maysamsh/QJDjh/4/