【问题标题】:Float not working when used with child inline-block element与子内联块元素一起使用时浮动不起作用
【发布时间】:2017-01-03 12:54:40
【问题描述】:

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

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

HTML

标题示例

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


<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; 
}

【问题讨论】:

  • 并不是inline-block元素不起作用,而是因为一旦在容器上声明了float,容器的宽度就不再跨越整个宽度了

标签: html css layout css-float sidebar


【解决方案1】:

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

发生了什么……

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

h1 标记正在清除您的浮动。通过为侧边栏本身或h1 标签设置宽度,浮动可以工作。为侧边栏设置宽度也会限制子h1 标签的宽度。

【讨论】:

    猜你喜欢
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多