当段落长于一行时,浮动属性不起作用

时间:2019-02-20 07:36:14

标签: html css css-float

我试图使用<p> css属性将左侧的float: left;元素对齐。

当文本在一行上时,它在左侧正确对齐,如下图所示: enter image description here

但是当文本至少为两行时,由于它从text-align: center;继承了body属性,因此文本不再左对齐并居中了: enter image description here

我知道我可以从text-align中删除body属性,但是我想知道它为什么会发生。

有人知道为什么吗?预先感谢。

这是html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Float test</title>
    <link rel="stylesheet" href="./css/styles.css">
</head>

<body>
        <div class="left-container">
            <div class="left-container-heading">Lorem Ipsum</div>
            <br>
            <br>
            <p>Float left doesn't work anymore since it is more than one line and I would like to know why and how to fix this.
            </p>
        </div>
</body>
</html>

这是css:

body {
    padding-top: 2em;
    text-align: center;
    width: 900px;
    margin: auto;
}

p, h, div {
    font-family: 'Corbel';
}

p {
    margin: 0;
}

.left-container {
    border: 3px solid red;
    border-right: 1px solid red;
    float: left;
    width: 446px;
    height: 100%;
}

.left-container p {
    position: relative;
    float: left;
    margin-left: 5px;
}

.left-container-heading {
    text-decoration: underline;
    font-style: italic;
    font-weight: bold;
    float: left;
    margin-left: 5px;
}

2 个答案:

答案 0 :(得分:1)

之所以这样来是因为身体在中心对齐。一旦删除,它就会向左浮动

findView(key : uniqueKey , view : UIView)

for subview in view.subviews {
if subview.uniqueKey == key 
return subview       // and break 
else 
continue with recursively searching
}
body {
    padding-top: 2em;
   
    width: 900px;
    margin: auto;
}

p, h, div {
    font-family: 'Corbel';
}

p {
    margin: 0;
    float:left;
}

.left-container {
    border: 3px solid red;
    border-right: 1px solid red;
    float: left;
    width: 446px;
    height: 100%;
}

.left-container p {
    position: relative;
    float: left;
    margin-left: 5px;
}

.left-container-heading {
    text-decoration: underline;
    font-style: italic;
    font-weight: bold;
    float: left;
    margin-left: 5px;
}

答案 1 :(得分:1)

因为当您的内容为1行时,您的p元素只会占用很小的空间,只是您没有意识到它就居中对齐,请尝试将宽度100%添加到p元素看看是否已更改。

当内容为2行时,p元素的宽度将采用最长的行的宽度,并且内容仍居中,并且您发现其居中对齐。

相关问题