与子内联块元素一起使用时浮动不起作用

问题描述 投票:0回答:1

我正在尝试创建一个布局,其中有一个侧边栏,如标题和介绍,旁边是一个卡片网格。但是,当我尝试使用float时,显示:div的子元素的内联块样式似乎会导致问题(当我在子元素上使用display:block时它会起作用)。任何替代解决方案都很受欢

https://jsfiddle.net/e_video/hdd0wr1p/

HTML

Title Example

描述不同主题的不同事物。


<div class="sidebar">
  <h1>
    Title Example
  </h1>
  <p>
  Descrition of different things on different subjects.
  </p>
</div>
<div class="card-section">
  <article class="card"></article>
  <article class="card"></article>
  <article class="card"></article>
  <article class="card"></article>
  <article class="card"></article>
  <article class="card"></article>
</div>
<br/>

CSS

.card{
  background: red;
  width:100px;
  height: 100px;
  display: inline-block;
  margin: 20px;
}

.card-section,
.sidebar{
  float:left; 
}
html css layout css-float sidebar
1个回答
0
投票

工作正常,你只需声明宽度小于100% - https://jsfiddle.net/hdd0wr1p/2/https://jsfiddle.net/hdd0wr1p/4/https://jsfiddle.net/hdd0wr1p/5/

发生了什么...

h1是一个旨在清除其他元素的块元素。默认情况下,h1是一个块,其宽度为其父元素的100%。在这种情况下,侧边栏上没有宽度,即窗口宽度的100%。

这是h1标签清除您的浮动。通过将宽度设置为侧边栏本身或h1标签,浮动工作。将宽度设置为侧边栏也会限制子h1标签的宽度。

© www.soinside.com 2019 - 2024. All rights reserved.