浮动元素破坏布局

时间:2014-07-29 17:54:53

标签: html css

我有一个巨大的弹出窗口。如果我想浮动一个元素,使两个元素彼此相邻,则弹出窗口的布局会被破坏。

通过将图像和文字放在彼此旁边,用" float:left"来看待自己:

http://jsfiddle.net/a7Vj8/1/

当我想浮动图像和文本时,白色背景变小。问题出在哪儿?当我使用" float:left"。

时,总会发生这种情况

这是我的HTML:

<div id="modal_profile_organisor" class="white_modal mfp-hide">

                    <div class="modal_padding">

                            <h3>Organisor</h3>

                            <div class="modal_organisor_details">

                                <img src="http://placehold.it/100x100">
                                <p>Some small text</p>



                            </div>


                    </div> <!-- /.modal_padding -->

                </div> <!-- /#modal_profile_organisor -->

<a href="#modal_profile_organisor" id="popup_organisor_modal">open modal</a>

2 个答案:

答案 0 :(得分:1)

.modal_organisor_details div的所有内容都浮动时,没有什么可以给容器任何大小。将overflow: auto添加到容器会创建一个新的float上下文,并解决:

.modal_organisor_details {
  text-align: center;
  font-size: 1.6em;
  margin-top: 10px;
  overflow: auto;
}

.modal_organisor_details img, .modal_organisor_details p
{
  float: left;
}

示例:http://jsfiddle.net/a7Vj8/2/

答案 1 :(得分:1)

如果您使用floats,则必须clear这些浮点数位于您不再需要浮动元素的位置,例如使用clear: both;

正在运作 fiddle

以下是HTML5 BOILERPLATE使用的clearfix课程:

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/*
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */

.clearfix {
    *zoom: 1;
}

使用此功能,您可以将clearfix类设置为浮动元素的包装容器。