2013-01-31 75 views
0

我有一个父div和一个子div.I想中心知道我是否可以表示宽度和高度作为父母的百分比,例如居中根据父div的子div

<!doctype html> 
<head> 
<meta charset='utf-8' /> 
<title>Horizontal center a div</title> 
<style type='text/css'> 
.one{ 
width:800px; 
height:100px; 
background-color:grey; 
} 
.two{ 
margin-top:30px; 
margin-bottom:30px; 
min-height:40px; 
margin-left:30px; 
width:90px; 
background-color:pink; 
display:inline-block; 
} 
</style> 
</head> 
<body> 
<div class="one"> 
<div class="two">lorem ipsum</p> 
</div> 
</body> 
</html> 

要看到它在行动http://jsfiddle.net/thiswolf/3qRgH/

外格(父)具有height of 100px和我的孩子div有一个height of 40px。我想居中父主题在我的孩子,所以,100px - 40px = 60px和我将60px分为两次,并指定子div margin-top:30pxmargin-bottom:30px;。我howev呃想以百分比的形式表达利润率。我将如何表达利润率%。

+0

如果。一是宽度是固定的,你可以自己算算,并表达百分之它,如果你的变量可以使用JavaScript实时更改它。见http://www.w3schools.com/css/css_margin.asp – dotoree

+0

在这种情况下,简单的答案是30%,但那不是。 – Gandalf

回答

0

可以居中的div这样(编辑):

<!doctype html> 
<head> 
<meta charset='utf-8' /> 
<title>Horizontal center a div</title> 
<style type='text/css'> 
.one{ 
width: 800px; 
background-color: grey; 
} 
.two{ 
min-height: 40px; 
margin: 30% 355px; 
width: 90px; 
background-color: pink; 
display: inline-block; 
} 
</style> 
</head> 
<body> 
<div class="one"> 
<div class="two">lorem ipsum</div> 
</div> 
</body> 
</html> 

http://jsfiddle.net/3qRgH/2/

这是你在问什么?

+0

我试图避免显示:block ;. – Gandalf

0

http://jsfiddle.net/thiswolf/5AZJD/

这似乎工作,但我还没有证明它

<!doctype html> 
<head> 
<meta charset='utf-8' /> 
<title>Horizontal center a div</title> 
<style type='text/css'> 
.one{ 
position:relative; 
width:800px; 
height:100px; 
background-color:grey; 
} 
.two{ 
position:absolute; 
top:30%; 
bottom:30%; 
min-height:40px; 
margin-left:30px; 
width:90px; 
background-color:pink; 
display:inline-block; 
} 
</style> 
</head> 
<body> 
<div class="one"> 
<div class="two">lorem ipsum</p> 
</div> 
</body> 
</html>