向左浮动元素和向右浮动元素被标题向上推 (chrome)

Float left element and float right element get pushed up by a heading (chrome)

我有一个 div 向左浮动,另一个 div 向右浮动,还有一个 div 在中间包含一个标题,当页面变窄并且 div中间的被向下推,这是预料之中的,但它也会将左右 div 推到容器上方和上方,这就是问题所在。

demo:https://jsfiddle.net/3rnjq0vb/,需要调整预览大小才能看到问题

它似乎在 edge and fire 上按预期工作

.left {
    float: left;
    background-color: tomato;
    height: 50px;
    width: 200px;
}

.right {
    float: right;
    background-color: cyan;
    height: 50px;
    width: 700px;
}

.center {
    display: inline-block;
}

body {
    text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="left">left</div>
    <div class="right">right</div>
    <div class="center">
        <h2>Some-text</h2>
    </div>
</body>
</html>

你可以做的一件事是给中心元素一个特定的宽度 - 容器的宽度减去其他两个元素的宽度,然后也浮动它。

width: calc(100% - 900px);

它需要设置最小宽度,否则当视口变窄时它会被压扁不存在。

这是一个片段:

.left {
  float: left;
  background-color: tomato;
  height: 50px;
  width: 200px;
}

.right {
  float: right;
  background-color: cyan;
  height: 50px;
  width: 700px;
}

.center {
  display: inline-block;
  float: left;
  width: calc(100% - 900px);
  min-width: 150px;
}

body {
  text-align: center;
}
<body>
  <div class="left">left</div>
  <div class="right">right</div>
  <div class="center">
    <h2>Some-text</h2>
  </div>
</body>

对于更具响应性的方法 - 例如,当视口变化时两侧元素的宽度发生变化,您可以根据您在较窄的视口上想要的确切结果来研究 grid 或 flex。

不应再将浮动用于布局(尽管您仍然可以将它们用于最初的目的 - 在图像周围浮动文本)。 Flexbox现在得到广泛支持,更适合布局。

试试这个 HTML --->

<div class ="wrapper">
 <div class="left">left</div>  
 <div class="center">
        <h2>Some-text</h2>
    </div>
    <div class="right">right</div>
</div>

然后添加css->

    .left {
    background-color: tomato;
    height: 50px;
    width: 200px;
}

.right {
    background-color: cyan;
    height: 50px;
    width: 700px;
}

.center {
    height: auto;
    width:200px;
}

.wrapper{
  display: flex;
  flex-direction: row;
   flex-wrap: wrap;
  width: 100%;
}

body {
    text-align: center;
}

这似乎是 chrome & opera 上的错误。在这种情况下,如果内联块组件的高度大于向左浮动的组件,它将出于某种原因将浮动元素推出容器。

我目前的 hacky 解决方案是降低内联元素的高度 https://jsfiddle.net/4ud7vemL/

    <div class="center">
        <h2 class="center-text">Some-text</h2>
    </div>
.center-text {
  line-height: 1;
  margin: 0;
}