垂直对齐div以获取响应式模板

时间:2013-10-24 08:27:41

标签: css html vertical-alignment

如何在div中创建文本:" grid2"和"第2和第34条;在中间垂直对齐?

这是我的HTML中的问题还是我的问题发生在CSS中?有人能指出我正确的方向吗?

我已经尝试过查看其他问题,但答案并没有让我更进一步。

我的HTML:

<html>
<head>
    <title></title>
</head>
<body>
<div id="background">
 <div id="template">  
  <div class="grid2">
   <div class="section2">
    <h2 style="text-align: center;">New 2014 Model</h2>
    <p>Latest model forced air (with a fan) fully automatic 48 egg incubator.</p>
    <p>This new design uses a sophisticated program for automated hatching process that    produces one of the highest hatching rates of any model, yet is incredibly easy to use.  Perfect for small hatchers, self sufficient households, or families incubating in the backyard.</p>
   </div>
  </div>
</div>

<!--responsive-->

我的CSS:

body {
margin:0px;
padding:0px;
} 
.clear {
clear:both;
} 
#background {
background-color:#FFFFFF; 
background-position:top;
width:100%;
max-width:1000px;
margin:auto;
} 
#template {
padding:10px;
font-family:Arial, Helvetica, sans-serif;
color:#000;
font-size:16px;
} 
.responsive {
width:100%;
} 
.grid2 {
float: left;
width:50%;
min-width:280px;
}
.grid3 {
float: left;
width:33.3%;
min-width:280px;
} 
.grid4 {
float: left;
width:16.66%;
min-width:160px;
} 
.section4 {
padding:1px;
} 
.section3 {
padding:5px;
} 
.section2 {
padding:10px;
}
.shrinkable {
clear: both;
padding: 0px;
margin: 0px; 
text-align:center;
} 
.shrinkable img {
width:60%;
height: auto;
} 
.shrinkable p {
text-align:center;
} 
.column {
display:block;
float:left;
margin: 1% 0 1% 1.6%;
} 
.column:first-child {
margin-left: 0;
} 
.box {
width: 32.2%;
} 
.row:before,.row:after {
content:"";
display:table;
} 
.row:after {
clear:both;
}

这是 the working example

4 个答案:

答案 0 :(得分:1)

这将使文本垂直和水平居中

.grid2 {height: 100%; display:table; text-align: center}
.section2 {display: table-cell; vertical-align: middle}

答案 1 :(得分:0)

添加CSS-Class

p {
   text-align: center;
}

或添加内联样式,就像在标题中所做的那样:

<p style="text-align: center;>Latest model forced air (with a fan) fully automatic 48 egg incubator.</p>
<p style="text-align: center;>This new design uses a sophisticated program for automated hatching process that produces one of the highest hatching rates of any model, yet is incredibly easy to use. Perfect for small hatchers, self sufficient households, or families incubating in the backyard.</p>

答案 2 :(得分:0)

试试看,然后看看。

.grid2  {float:left; height:50%; margin-bottom:-120px;}
.section2   {clear:both; height:240px; position:relative;}

答案 3 :(得分:-1)

由于它具有响应性,我发现最好的方法不依赖于CSS,因为如果它真的有响应,就不应该有任何设定的高度。

最好的方法是使用jquery查找父div的高度,然后根据该值对齐所需的text / image / div。这可以使用jquery resize函数计算,这意味着当尺寸发生变化时,它将保持居中。

有些事情:

$( window ).resize(function() {
   var changeheight = $('.parentdiv').height() / 2;
   $('.div').css('margin-top', changeheight)
});

但是你需要将你所在的div的大小计算在计算中。