How can fixed element push content down the page using CSS only?

半腔热情 提交于 2019-12-10 15:27:36

问题


I've seen similar question asked here before but answers usually include Jquery etc. I'm rookie and I want to use CSS only. I have a web page and there is a text displayed on it:

<P>yes yes yes </P>
<P>yes yes yes </P>
<P class="move">Moving part</P>

I want the last part (class move) to move on the top when screen is small. This works great:

.move {
    color: blue;
}
@media screen and (max-width: 600px) {
    .move {
        position: fixed;
        top: 0px;
    }
}

Except "Moving part" is displayed over text! How can I push the text down. I've tried height, etc.


回答1:


There is position: sticky, but it's only supported in FireFox and Safari.

Unfortunately there is no way to mimic this for other browsers without JavaScript.

To do this requires the top to be calculated and modified as you scroll down the page. I've looked for a CSS only solution myself and it doesn't seem to exist, nor did my attempts work.

Have a look at the stickyMojo jQuery plugin or Bootstrap affix.




回答2:


Wrap the code into a div and give it a margin-top when the screen gets smaller. That´s the only thing i could imagine that could work in all browsers with only using CSS. Your "move"-element should have a fixed height then. For example:

<div class="move-mobile">
  <P>yes yes yes </P>
  <P>yes yes yes </P>
</div>
<P class="move">Moving part</P>

CSS

.move {
    color: blue;
    height: 50px;
}
@media screen and (max-width: 600px) {
    .move {
        position: fixed;
        top: 0px;
    }

    .move-mobile {
        margin-top: 50px;
    }
}

or make two move elements, the one is hidden and only gets visible when the screen gets smaller, the other one is hidden then.



来源:https://stackoverflow.com/questions/31782665/how-can-fixed-element-push-content-down-the-page-using-css-only

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