html - 两个 div 的边框与 `display: inline-block` 并排

标签 html css

我已经使用 display: inline-block 和以下代码 ( jsFiddle ) 并排对齐两个 div 元素:

<html>
  <head>
    <style>
     #a {
       border: 10px solid red;
       width: 200px;
       height: 200px;
       background: black;
       font-size: 0;
     }
     #a1 {
       font-size: 16px;
       border: 10px solid green;
       width: 100px;
       height: 200px;
       background: white;
       box-sizing: border-box;
       display: inline-block;
     }
     #a2 {
       font-size: 16px;
       border:  10px solid green;
       width: 100px;
       height: 200px;
       background: white;
       box-sizing: border-box;
       display: inline-block;       
     }     
    </style>
  </head>
  <body>
    <div id='a'>
      <div id='apadding'>
        <div id='a1'>a1</div>
        <div id='a2'>a2</div>
      </div>
    </div>
  </body>
</html>

以上产生了以下期望的结果:

enter image description here

我可以更改两个 div 元素的边框,并且(只要它们具有相同的边框)结果就是预期的结果。

但是,当我仅将第二个 div 的边框更改为例如20 像素这是我得到的 ( jsFiddle ):

enter image description here

鉴于两个内部 div 元素的 box-sizing 都设置为 border-box 我期待边框宽度的任何变化被那个 div 的框吸收并且不以任何方式破坏对齐。更令人费解的是,第二个 div(其边框已更改)最终正确显示,而第一个 div 不知何故被推离了它的位置。

我错过了什么?

最佳答案

因为边框现在包含在宽度中,所以内容框会相应缩小。这会影响该 div 的 baseline

由于行内 block 元素默认与基线垂直对齐,因此只需将其设置为 top 即可解决问题。

#a {
  border: 10px solid red;
  width: 200px;
  height: 200px;
  background: black;
  font-size: 0;
}
#a1 {
  font-size: 16px;
  border: 10px solid green;
  width: 100px;
  height: 200px;
  background: white;
  box-sizing: border-box;
  display: inline-block;
}
#a2 {
  font-size: 16px;
  border: 20px solid green;
  width: 100px;
  height: 200px;
  background: white;
  box-sizing: border-box;
  display: inline-block;
}
#a1,
#a2 {
  vertical-align: top;
}
<div id='a'>
  <div id='apadding'>
    <div id='a1'>a1</div>
    <div id='a2'>a2</div>
  </div>

关于html - 两个 div 的边框与 `display: inline-block` 并排,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38460979/

相关文章:

javascript - 避免在元素上绑定(bind)多个事件

javascript - 如何从执行 Stripe Integration 的 Controller 中获取 DOM 元素?

html - 堆叠不同的 HTML 元素;哪个在哪个之上?

html - rails : How to add custom data-attributes in collection_select

html - 如何使用 CSS 应用渐变?

c# - 如何使用 ASP.NET MVC 返回动态 CSS?

iphone - 子类 UIButtons

javascript - htaccess - 将单个 html 页面重定向到 https

html - 两个 div 在 html 和 CSS 中没有水平对齐

html - 所选选项宽松的红色