【问题标题】:text-align:center not working with div elements文本对齐:中心不适用于 div 元素
【发布时间】:2013-06-15 04:52:33
【问题描述】:

我已经搜索了大约 45 分钟,但在这里找不到我的问题的解决方案。我希望我的画廊类 div(这些将动态创建)仅使用 css 规则将它们自身对齐在 gallery_container div 的中心。我正在学习,所以任何解释都会有所帮助!

提前致谢!

<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>

这里是小提琴http://jsfiddle.net/9gwKc/1/

【问题讨论】:

  • 您的问题是您已将 .gallery css 类标记为 display: inline;。您希望如何将您告诉浏览器堆叠在一起的元素居中对齐?
  • 我明白了,我在测试时将代码留在了那里。当它被移除时,我看不出有任何区别。
  • 我什至没有注意到我忘记了那些引号!但它在 chrome 中就像那样工作(否则我会抓住它)。谢谢回复!不过,它仍然对我的问题没有帮助:(

标签: html layout center text-align


【解决方案1】:

这可以通过使用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;
}

【讨论】:

  • 只是为了强调而添加此评论,因为我第一眼就错过了关键点-您必须删除 float: left; 在添加display: inline-block; 之前添加text-align在这里做你想做的事。
猜你喜欢
相关资源
最近更新 更多
热门标签