Html text-align:center 不适用于 div 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17177950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
text-align:center not working with div elements
提问by Doctor Parameter
I've been searching for about 45 minutes and couldn't find a solution for my issue here. I want my gallery class divs (these will get created dynamically) to align them selves in the center of the gallery_container div using only css rules. I'm learning so any explanation would be helpful!
我已经搜索了大约 45 分钟,但在这里找不到解决我的问题的方法。我希望我的画廊类 div(这些将动态创建)仅使用 css 规则将它们自己对齐到 gallery_container div 的中心。我正在学习,所以任何解释都会有帮助!
Thanks in advance!
提前致谢!
<head>
<style>
#gallery_container{
text-align: center;
width:100%;
overflow: auto;
background:orange;
}
.gallery{
text-align: left;
border-style: solid;
border-width:3px;
border-top-left-radius: 40px;
border-bottom-right-radius: 40px;
background:yellow;
width:335px;
padding:20px;
float:left;
margin:15px;
}
.gallery h2{
margin-top:0;
}
.gallery img{
height:120px;
width:160px;
float:right;
}
</style>
<body>
<div id ='content_gallery'>
<h2>Gallery</h2>
<div id='gallery_container'>
<div class = gallery>
<img src = 'bowling_01.png'>
<h2>Company bowling</h2>
<h4>Date: June 14, 2013</h4>
<p>The company heads to Boca Bowl for our monthly bowling event!</p>
</div>
<div class = gallery>
<img src = 'bowling_01.png'>
<h2>Company bowling</h2>
<h4>Date: June 14, 2013</h4>
<p>The company heads to Boca Bowl for our monthly bowling event!</p>
</div>
<div class = gallery>
<img src = 'bowling_01.png'>
<h2>Company bowling</h2>
<h4>Date: June 14, 2013</h4>
<p>The company heads to Boca Bowl for our monthly bowling event!</p>
</div>
</div>
</div>
</body>
and here the fiddle http://jsfiddle.net/9gwKc/1/
回答by Doctor Parameter
This can be done with by using an inline-block
display, the float:left
will always send the elements to their furthest left possible.
这可以通过使用inline-block
显示器来完成,float:left
它将始终将元素发送到尽可能最左侧。
.gallery {
text-align: left;
border-style: solid;
border-width:3px;
border-top-left-radius: 40px;
border-bottom-right-radius: 40px;
background:yellow;
width:335px;
padding:20px;
/*float:left; remove this*/
margin:15px;
/*add this*/
display:inline-block;
position:relative;
}