如何在一个较大的div中居中两个div?

时间:2013-04-22 09:26:14

标签: css

我正在尝试将两个div(#about#testimonial-snippets)置于较大的黑色div中。我怎么能这样做?

JS小提琴:http://jsfiddle.net/DgtqM/

HTML

<footer>
        <div id="footer-section">
            <section id="about">
                <a href="http://twitter.com" target="_blank"><img class="profile-photo" src="http://dummyimage.com/42x42/000/fff" alt="profile" height="44" width="44"></a>
                <p>Lorem ipsum dolor sit amet. Find him on <a href="http://twitter.com" target="_blank">Twitter</a> and <a href="http://instagram.com" target="_blank">Instagram</a>. <a id="slide-toggle" href="#">Contact</a> | <a href="">Archive</a></p>
            </section>
            <section id="testimonial-snippets">
                <a href="http://twitter.com" target="_blank"><img class="profile-photo" src="http://dummyimage.com/42x42/000/fff" alt="profile" height="44" width="44"></a>
                <div class="snippet">
                    <p>This is a testimonial.</p>
                    <a class="read-testimonial" href="/testimonials">read more</a>
                </div>
            </section>
        </div>
</footer>

CSS

footer {
background: #222;
clear: both;
color: #f4f3f1;
float: left;
padding: 50px 0;
width: 100%;
}
#footer-section {
margin: 0 auto;
overflow: hidden;
position: relative;
width: 940px;
}
footer section {
float: left;
width: 300px;
}
#about {
margin-right: 20px;
}
footer a {
border-bottom: 1px dotted #f4f3f1;
color: #f4f3f1;
}
.profile-photo {
border: 1px solid #f4f3f1;
float: left;
margin: 4px 10px 10px 0;
}
p {
margin: 0 0 1em;
}

2 个答案:

答案 0 :(得分:3)

我允许自己将该问题减少到最小标记。其他一切与问题无关,只会让人更难理解。

<footer>
    <section id="about">About</section>
    <section id="testimonial-snippets">Testimonial</section>
</footer>

一种解决方案是制作这些inline-block个元素,并将它们放在页脚的中心位置:

footer {
    background: #222;
    padding: 50px 0;
    width: 100%;
    text-align: center;
}
footer section {
    width: 300px;
    height: 50px;
    display: inline-block;
    text-align: left;
}
/* Just coloring the different divs */
#about { background: red; }
#testimonial-snippets { background: green; }

http://jsfiddle.net/DgtqM/6/

答案 1 :(得分:0)

将元素包装在新div中。然后给新div一个固定的宽度并使用margin: 0px auto进行样式化。

<强> HTML

<div id="footer-section">
   <div class="wrap">
    <section id="about">
      <!--Content -->
    </section>
    <section id="testimonial-snippets">
      <!--Content-->
    </section>
   </div>
</div>

<强> CSS

.wrap{
    width: 620px;
    margin: 0px auto;
    overflow: auto;
}

示例 http://jsfiddle.net/DgtqM/5/