CSS offset in Bootstrap-like grid

ε祈祈猫儿з 提交于 2019-12-11 02:34:02

问题


I'm trying to recreate Bootstrap's offset in its desktop grid whereby a class like .col-md-offset-3 creates an offset via margin-left .

For some reason, in my attempt, this CSS selector fails (i.e. the div is not offset):

.col-offset-8 {margin-left ... }

But both of these succeed:

div.col-offset-8 {margin-left ... }

col-4.col-offset-8 {margin-left ... } /*note: multiple class selectors, no space */

Why won't .col-offset-8 work by itself?

Here's my CodePen.

@media all and (min-width:760px) {
  .row {margin:0 auto;overflow:hidden;}
  .row > div {margin:10px;overflow:hidden;float:left;display:inline-block;}
  .row {width:960px;}
  .col-8 {width:620px} .col-4 {width:300px}
  .col-12 {width:940px} .col-6 {width:460px}
  .col-offset-8 {
    margin-left:650px; /* = col-8 + margins */
  }
}

/* for demo */
.row {background:#ccc}
.row > div {background:#eee; outline:1px solid #444}
p {font:24px/60px Arial;color:#000;text-align:center}
<div class="row">
  <div class="col-12">
    <p>col-12</p>
  </div>
</div>

<div class="row">
  <div class="col-4 col-offset-8">
    <p>col-4 offset-8</p>
  </div>
</div>

<div class="row">
  <div class="col-8">
    <p>col-8</p>
  </div>
  <div class="col-4">
    <p>col-4</p>
  </div>
</div>

<div class="row">
  <div class="col-12">
    <p>col-12</p>
  </div>
</div>

回答1:


It's not working because the selector .row > div is more specific than .col-offset-8.

More precisely, .row > div has a specifity value of 11 whereas .col-offset-8 has a value of 10.

Because of this, the margin: 10px from .row > div is overwriting the margin-left

You could increase the specifcity of your selector from .col-offset-8 to .row .col-offset-8. In doing to margin-left will overwrite margin: 10px.

Updated Example

.row .col-offset-8 {
  margin-left: 650px; /* = col-8 + margins */
}

For what it's worth, this is a nice tool for calculating specificity.



来源:https://stackoverflow.com/questions/28615263/css-offset-in-bootstrap-like-grid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!