我正在使用css3开发移动HTML5页面,我正在使用如下页面
<!DOCTYPE html>
<html>
<head>
<title>Starter page</title>
<style>
.float-right{float:right}
.float-left{float:left}
.clear{clear:both}
</style>
</head>
<body>
<div class="content" id="home">
<div class=" ">
<!--START: Div to be centered to page-->
<div class="DivToBeCentered">
<div class="float-left">
<!--START: This paragraph content is dynamic from database, i want to center align the div with the class
DivToBeCentered with reference to its parent-->
<p class="">dynamic para 1 with background image</p>
<!--END: This paragraph content is dynamic from database, i want to center align the div with the class
DivToBeCentered with reference to its parent-->
</div>
<div class=" float-left">
<p class="">static para 2 without background image</p>
</div>
<div class="clear"></div>
</div>
<!--END: Div to be centered to page-->
</div>
</div>
</body>
</html>
我想将div与上面代码中的“DivToBeCentered”类水平居中对齐到其父div。在div中有两个段落标记,因为一个段落标记内容是动态的,因此在加载页面时它的宽度可能会发生变化,我如何将该div与“DivToBeCentered”类对齐到其父级。如果你解决这个问题对我来说会更有帮助,我在这个问题上遇到了困难。谢谢你提前
答案 0 :(得分:3)
简单的解决方案是display: inline-block;
DivToBeCentered
和text-align:center;
outer
div
<强> DEMO 强>
要更改的Css
.outer {text-align:center;}
.DivToBeCentered {display: inline-block;}
<html>
<head>
<title>Starter page</title>
<style>
.float-right{float:right}
.float-left{float:left}
.clear{clear:both}
.outer {text-align:center;}
.DivToBeCentered {display:block-inline}
</style>
</head>
<body>
<div class="content" id="home">
<div class="outer">
<!--START: Div to be centered to page-->
<div class="DivToBeCentered">
<div class="float-left">
<!--START: This paragraph content is dynamic from database, i want to center align the div with the class
DivToBeCentered with reference to its parent-->
<p class="">dynamic para 1 with background image</p>
<!--END: This paragraph content is dynamic from database, i want to center align the div with the class
DivToBeCentered with reference to its parent-->
</div>
<div class=" float-left">
<p class="">static para 2 without background image</p>
</div>
<div class="clear"></div>
</div>
<!--END: Div to be centered to page-->
</div>
</div>
</body>
答案 1 :(得分:1)
试试这个:
<div class="content" id="home">
<!--START: Div to be centered to page-->
<div class="DivToBeCentered">
<div class="float-left">
<!--START: This paragraph content is dynamic from database, i want to center align the div with the class
DivToBeCentered with reference to its parent-->
<p class="">dynamic para 1 with background image</p>
<!--END: This paragraph content is dynamic from database, i want to center align the div with the class
DivToBeCentered with reference to its parent-->
</div>
<div class=" float-left">
<p class="">static para 2 without background image</p>
</div>
<div class="clear"></div>
</div>
<!--END: Div to be centered to page-->
</div>
CSS:
.content{
position: relative;
}
.DivToBeCentered{
position: absolute;
left: 0;
right: 0;
/*for vertical centering*/
/*
top:0;
bottom:0;
*/
margin: auto;
}