Contacts

Fixed two-column layout. Fixed Top Menu and Floating Sidebar in WordPress The Most Working Way

What are the layout requirements?

  • Rubber two-column layout
  • sidebar fixed width 300px
  • content is stretched to the rest of the width.
  • footer pressed to the bottom (in this tutorial I will not show how this is done).

What Css problems arise when laying out such a layout:

1 way.

If you float blocks, you must give them a fixed width(you can't set 1 sidebar to 300px and content to 100%). In this case, either the content slides down or a 300px horizontal scroll to the left appears. Well, the main thing to understand is that this method does not suit us.


2 way.

Many typesetters offer this method, what are they thinking about?! The essence of the method is that you can set the sidebar to float with a width of 300, and not float the content and set margin-left: 300px to it. A good way and everything seems to work so well. To be honest, I thought this was the best way, but this method has its own pitfalls. The reasons for abandoning this method are that if we suddenly make up in the content, for example, a menu with floated li or any other float blocks and then we want to clear them with clear:both, then the bottom border of this block slides down to the level of the bottom border of the sidebar (What and it's not strange since foat is cleared, you can avoid this if set a floated block to a fixed height, but it's not at all the case to set a fixed height).


3 way.

Can be used for sidebar position absolute but only if you we are sure that the content will be larger than the sidebar in height otherwise, the entire contents of the sidebar will fit on the footer (after all, absolute positioning pulls out of the general flow).

But as for me, this is also not a very good way!


4 way.

"Great way, if it has any flaws please comment. But I think this is the best way."

  • Advantages of this method: firstly, the DOM content will go before the sidebar, which is good for search engines.
  • nothing will fit on the footer
  • any blocks can be cleared and nothing will slide to the lower border (So we overcame the problems of the second method).

In general, how it works: look at the code first comes content followed by sidebar. we set float to these two blocks (of course the sidebar slides down). after that we set the sidebar property margin-left:-100%. great, it's back in place, and indent the content with margin-lerft:300px.


html

css

.sidebar(
width:300px;
display:block;
float: left;
margin: 0 0 0 -100%;
}
.content(
min-width:723px;
display:block;
float: left;
margin: 0 0 0 220px;
}

A floating block (or as it is also called moving, fixed, stuck) is needed on the site so that the user sees one fixed element when scrolling the page, in which advertising is most often placed (teasers, banners or context).

Alas, the rules of adsense forbid us this. However, many site owners ignore the rules at their own risk. Maybe they are not even punished for this, but I would not advise taking risks.

I place YAN, my teasers / banners in such blocks, and sometimes, instead of advertising, I display similar posts or some useful information for the visitor.

Let's tell you how you can make a floating block on your site.

Task: make the last block in the sidebar (sidebar) floating. Moreover, so that it sticks only at the moment when the user reaches it by scrolling, and not immediately when the page is opened. Also, the block should “stick off”, reaching the footer (i.e. not overlapping it).

The most working way

There are many implementations of the sticky block, but not all of them work correctly. I’ll tell you from personal experience: the same block installation method can work on one site, and jambs will appear on another.

Below is an example of a floating block that has worked on almost every site I've installed it on. There were no goats. The engine is also not important (DLE, WordPress, LiveStreet, etc.).

Paste the following HTML code in the desired location of the sidebar:

$(window).scroll(function() (
var sb_m = 20 ; /* top and bottom padding */
var mb = 300 ; /* basement height with margin */
varst = $(window).scrollTop() ;
var sb = $(".sticky-block" ) ;
var sbi = $(".sticky-block .inner" ) ;
var sb_ot = sb.offset() .top;
var sbi_ot = sbi.offset() .top;
var sb_h = sb.height () ;

If(sb_h + $(document).scrollTop() + sb_m + mb< $(document) .height () ) {
if(st > sb_ot) (
var h = Math.round(st - sb_ot) + sb_m;
sb.css(("paddingTop" : h) ) ;
}
else(
sb.css(( "paddingTop" : 0 ) ) ;
}
}
} ) ;

In this code, you can set the padding at the top, bottom, as well as the height of your footer, i.e. the height at which the block should stop.

Now we include JS. To do this, write in the HEAD section:



вставляем:



Результат данного примера показан на рис. 5.12.

Рис. 5.12. Двухколоночный макет

Для слоя content поля включаются через свойство padding , но поскольку ширина слоя не указана, то поля никак на неё не повлияют. В слое sidebar вставлен список, у которого отступы установлены по умолчанию, поэтому никакого «налипания» текста на край фона нет. К подвалу (слой footer ) добавляется свойство clear , которое отменяет действие float . Оно требуется на тот случай, когда высота навигации превышает высоту контента, чтобы текст не накладывался на подвал.

Самый простой пример фиксированного плавающего сайдбара на HTML+CSS+JS.

В чем его особенность – при прокрутке сайдбар прилипает к верхней части окна, но при этом, когда сайдбар прокручивается до футера, тогда он отлипает от верхней части экрана и прилипает своей нижней частью к футеру, тем самым не перекрывая собой футер (футер должен быть высоким). Если вы понимаете, о чем я.

Пример взят с какого-то сайта и он очень примитивный (и устаревший морально), подходит только для данной верстки. Более универсальный код можно посмотреть в этой статье и уже самостоятельно писать свой код под свой проект.

HTML-разметка простой страницы

HEADER
CONTENT

CSS-стили для блоков контента

.header { width: 100%; background: purple; height: 80px; } .content { width: 80%; background: blue; height: 800px; float: left; } .sidebar { width: 20%; background: green; height: 100px; float: right; } .sidebar.fixed { position: fixed; right: 50%; margin-right: -50%; } .footer { width: 100%; background: gray; height: 500px; clear: both; }

JS-скрипт для фиксированного сайдбара при прокрутке страницы

Не забываем подключить jQuery

$(function() ( var $window = $(window); var $sidebar = $(".sidebar"); var $sidebarTop = $sidebar.position().top; var $sidebarHeight = $sidebar.height() ; var $footer = $(".footer"); var $footerTop = $footer.position().top; $window.scroll(function(event) ( $sidebar.addClass("fixed"); var $scrollTop = $window.scrollTop(); var $topPosition = Math.max(0, $sidebarTop - $scrollTop); if ($scrollTop + $sidebarHeight > $footerTop) ( var $topPosition = Math.min($topPosition, $footerTop - $scrollTop - $sidebarHeight); ) $sidebar.css("top", $topPosition); )); ));



Liked the article? Share it