pro pro - 11 days ago 5
CSS Question

Add a margin-top to a sibling div on condition that a top sibling has a fixed position

The dashboard and content classes are universal in the app (that means they are on every template or page). The header class is only available on certain pages.

<div class="dashboard">
<div class="header"></div>
<div class="content"></div>
</div>


What I want is, to add the rule 'fixed position to the header class and fix it to the top of the page on those pages that it exists and give it a white background across the window. Now, when I do that, the content inside the div with content class goes under the header. But, I want that content to have a top margin and be positioned under the header div on only the pages where the header exists.

I know I can add a top padding or margin to the content class, but that will affect all the pages with the content class, but I don't want that to happen?

How can I conditionally achieve this goal?

Answer

I think for pages where you have header followed by content ,you can apply styles as .header ~ .content and for other pages may be you can just style it as .content

check this snippet

.header{
  position:fixed;
  background:red;
  left:0;
  top:0;
  width:100%;
}
.header ~ .content{
  margin-top:50px;
  background:gray;
}
<div class="dashboard">
  <div class="header">khfdsfjksd</div>
  <div class="content">
    Lorem ipsum dolor sit amet, facilisis orci, risus accumsan mauris mi aliquam, mattis felis, condimentum vel arcu pellentesque vulputate et scelerisque. A mi ut arcu nunc odio, nunc aliquam, vel libero orci bibendum pellentesque. Placeat eget mauris tortor dignissim habitant, viverra nunc urna in. Massa lectus mauris felis nibh. Non imperdiet ut, cum vivamus soluta porta sed, quisque erat diam blandit dolor.Lorem ipsum dolor sit amet, facilisis orci, risus accumsan mauris mi aliquam, mattis felis, condimentum vel arcu pellentesque vulputate et scelerisque. A mi ut arcu nunc odio, nunc aliquam, vel libero orci bibendum pellentesque. Placeat eget mauris tortor dignissim habitant, viverra nunc urna in. Massa lectus mauris felis nibh. Non imperdiet ut, cum vivamus soluta porta sed, quisque erat diam blandit dolor.Lorem ipsum dolor sit amet, facilisis orci, risus accumsan mauris mi aliquam, mattis felis, condimentum vel arcu pellentesque vulputate et scelerisque. A mi ut arcu nunc odio, nunc aliquam, vel libero orci bibendum pellentesque. Placeat eget mauris tortor dignissim habitant, viverra nunc urna in. Massa lectus mauris felis nibh. Non imperdiet ut, cum vivamus soluta porta sed, quisque erat diam blandit dolor.
  </div>
</div>

<div class="content">
  sfhdskfdsk
</div>

In SCSS your code should be like this

.dash-board {
  .header {
    position: fixed;
    background: red;
    left: 0;
    top: 0;
    width: 100%;
    ~ .content {
      margin-top: 50px;
      background: gray;
    }
  }
}

hope it helps

Comments