CSS Positions

In order to make more complex layouts, we need to discuss the position property.

There are five different position values:

  • static
  • relative
  • fixed
  • absolute
  • sticky

position: static;

HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right properties.

An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page:

position: static;

position: relative;

An element with position: relative; is positioned relative to its normal position.

Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.

Usage :

position:relative;
top:10px;
left:20px;

position: fixed;

An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.

A fixed element does not leave a gap in the page where it would normally have been located.

Usage : 

position: fixed;
bottom: 0;
right: 0;

position: absolute;

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

position: absolute;

position: sticky;

An element with position: sticky; is positioned based on the user’s scroll position.

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport – then it “sticks” in place (like position:fixed).

Usage :

position : sticky;
top:0px;

Live Code Example : Download Here

320 thoughts on “CSS Positions

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. I’ve been exploring for a little bit for any high-quality articles or weblog posts on this kind of area . Exploring in Yahoo I finally stumbled upon this site. Reading this info So i’m glad to convey that I’ve an incredibly excellent uncanny feeling I found out exactly what I needed. I most unquestionably will make sure to do not fail to remember this site and give it a glance regularly.

  2. Thanks for another informative blog. Where else could I get that kind of information written in such a perfect way? I’ve a project that I am just now working on, and I have been on the look out for such info.

  3. Does your site have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail. I’ve got some ideas for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it expand over time.

  4. The subsequent time I learn a blog, I hope that it doesnt disappoint me as a lot as this one. I mean, I do know it was my option to read, but I really thought youd have something fascinating to say. All I hear is a bunch of whining about one thing that you would repair for those who werent too busy in search of attention.

  5. Simply desire to say your article is as astonishing. The clearness in your post is just nice and i can assume you are an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please keep up the rewarding work.

  6. Thank you for another fantastic article. The place else could anybody get that kind of information in such a perfect method of writing? I have a presentation subsequent week, and I’m at the look for such information.

  7. I enjoy you because of each of your hard work on this site. Kate take interest in managing investigation and it is easy to see why. My spouse and i notice all relating to the lively form you convey precious items via this web blog and as well as improve participation from people on this idea while my child is studying a lot of things. Take advantage of the rest of the new year. You’re the one performing a fantastic job.

  8. Hey just wanted to give you a quick heads up. The text in your post seem to be running off the screen in Opera. I’m not sure if this is a format issue or something to do with internet browser compatibility but I thought I’d post to let you know. The design and style look great though! Hope you get the issue resolved soon. Many thanks

  9. I have been exploring for a little for any high-quality articles or blog posts on this kind of area . Exploring in Yahoo I at last stumbled upon this website. Reading this information So i am happy to convey that I’ve an incredibly good uncanny feeling I discovered just what I needed. I most certainly will make sure to do not forget this web site and give it a glance on a constant basis.

  10. you’re really a good webmaster. The website loading speed is incredible. It seems that you are doing any unique trick. Furthermore, The contents are masterwork. you have done a magnificent job on this topic!

  11. Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site I hope you enjoy blogging with the popular BlogEngine.net.Thethoughts you express are really awesome. Hope you will right some more posts.

  12. Whats Taking place i am new to this, I stumbled upon this I’ve found It positively useful and it has helped me out loads. I am hoping to contribute & help other customers like its aided me. Good job.

  13. Good blog! I really love how it is easy on my eyes and the data are well written. I am wondering how I might be notified when a new post has been made. I have subscribed to your RSS feed which must do the trick! Have a nice day!

  14. Usually I don’t read post on blogs, but I would like to say that this write-up very forced me to try and do so! Your writing style has been surprised me. Thanks, quite nice post.

  15. I am not sure the place you’re getting your info, but great topic. I needs to spend some time studying much more or working out more. Thank you for fantastic info I was searching for this info for my mission.

  16. Thank you, I’ve just been searching for information approximately this topic for a long time and yours is the greatest I have came upon so far. But, what about the conclusion? Are you positive concerning the supply?

  17. Hey! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done a outstanding job!

  18. I’m really enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to create your theme? Exceptional work!

  19. I like what you guys are up also. Such smart work and reporting! Carry on the excellent works guys I’ve incorporated you guys to my blogroll. I think it’ll improve the value of my web site :).

  20. I found your blog site on google and check a couple of of your early posts. Continue to keep up the superb operate. I simply additional up your RSS feed to my MSN Information Reader. Looking for ahead to studying more from you in a while!…

  21. You could certainly see your enthusiasm within the work you write. The arena hopes for even more passionate writers like you who aren’t afraid to mention how they believe. All the time go after your heart.

  22. Undeniably believe that which you stated. Your favorite justification appeared to be on the net the easiest thing to be aware of. I say to you, I definitely get annoyed while people consider worries that they plainly don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people could take a signal. Will likely be back to get more. Thanks

  23. Excellent read, I just passed this onto a friend who was doing some research on that. And he actually bought me lunch as I found it for him smile Thus let me rephrase that: Thank you for lunch! “By nature, men are nearly alike by practice, they get to be wide apart.” by Confucius.

  24. Hi there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!

  25. What i don’t understood is actually how you are not really much more well-liked than you may be now. You are so intelligent. You realize thus significantly relating to this subject, produced me personally consider it from numerous varied angles. Its like men and women aren’t fascinated unless it is one thing to do with Lady gaga! Your own stuffs outstanding. Always maintain it up!

  26. I am glad for commenting to let you understand of the extraordinary encounter our child had reading through your site. She realized a lot of things, which include what it is like to have an awesome coaching style to let men and women quite simply master specified hard to do things. You undoubtedly did more than visitors’ desires. Thanks for imparting such priceless, safe, explanatory and even fun thoughts on the topic to Evelyn.

  27. Hello very nice website!! Guy .. Beautiful .. Amazing .. I’ll bookmark your website and take the feeds also…I’m satisfied to search out so many helpful information right here in the publish, we need work out more techniques on this regard, thanks for sharing.

  28. Woah! I’m really enjoying the template/theme of this site. It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance” between user friendliness and appearance. I must say you’ve done a superb job with this. In addition, the blog loads extremely fast for me on Safari. Superb Blog!

  29. Fantastic beat ! I would like to apprentice while you amend your site, how can i subscribe for a blog site? The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast provided bright clear concept

  30. Hey there! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be great if you could point me in the direction of a good platform.

  31. Wonderful beat ! I would like to apprentice while you amend your website, how can i subscribe for a blog web site? The account helped me a acceptable deal. I had been tiny bit acquainted of this your broadcast offered bright clear concept

  32. I think this is among the most significant info for me. And i’m glad reading your article. But should remark on few general things, The site style is great, the articles is really great : D. Good job, cheers

  33. This blog is definitely rather handy since I’m at the moment creating an internet floral website – although I am only starting out therefore it’s really fairly small, nothing like this site. Can link to a few of the posts here as they are quite. Thanks much. Zoey Olsen

  34. The other day, while I was at work, my cousin stole my apple ipad and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is entirely off topic but I had to share it with someone!

  35. After study a few of the blog posts on your website now, and I truly like your way of blogging. I bookmarked it to my bookmark website list and will be checking back soon. Pls check out my web site as well and let me know what you think.

  36. Hey there just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same results.

  37. Hi! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us beneficial information to work on. You have done a wonderful job!

  38. The other day, while I was at work, my cousin stole my apple ipad and tested to see if it can survive a 25 foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views. I know this is completely off topic but I had to share it with someone!

  39. Youre so cool! I dont suppose Ive learn something like this before. So nice to seek out any person with some original ideas on this subject. realy thanks for starting this up. this web site is one thing that is needed on the net, somebody with a bit originality. useful job for bringing something new to the internet!

  40. Fantastic beat ! I would like to apprentice whilst you amend your website, how could i subscribe for a blog site? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright transparent concept

  41. Having read this I thought it was very informative. I appreciate you taking the time and effort to put this article together. I once again find myself spending way to much time both reading and commenting. But so what, it was still worth it!

  42. Hey There. I discovered your weblog the use of msn. This is a very well written article. I’ll be sure to bookmark it and come back to read extra of your useful info. Thanks for the post. I’ll certainly comeback.

  43. I have learn some just right stuff here. Definitely worth bookmarking for revisiting. I wonder how so much effort you place to make the sort of fantastic informative site.

  44. Attractive section of content. I just stumbled upon your weblog and in accession capital to assert that I acquire actually enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access consistently fast.

  45. There are actually loads of particulars like that to take into consideration. That could be a nice point to carry up. I supply the ideas above as general inspiration however clearly there are questions like the one you carry up the place an important factor can be working in sincere good faith. I don?t know if greatest practices have emerged round issues like that, however I’m sure that your job is clearly identified as a fair game. Both boys and girls feel the influence of only a second’s pleasure, for the remainder of their lives.

  46. I’ve been surfing online more than 3 hours lately, but I never found any attention-grabbing article like yours. It is beautiful value enough for me. In my view, if all website owners and bloggers made excellent content as you did, the web might be much more useful than ever before.

  47. I’m really enjoying the theme/design of your weblog. Do you ever run into any browser compatibility issues? A few of my blog audience have complained about my site not working correctly in Explorer but looks great in Safari. Do you have any recommendations to help fix this issue?

  48. Hello, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam remarks? If so how do you reduce it, any plugin or anything you can recommend? I get so much lately it’s driving me crazy so any assistance is very much appreciated.

  49. excellent put up, very informative. I’m wondering why the opposite experts of this sector don’t realize this. You must proceed your writing. I’m confident, you’ve a huge readers’ base already!

  50. “”Nice read, I just passed this onto a friend who was doing a little research on that. And he just bought me lunch since I found it for him smile Therefore let me rephrase that Thank you for lunch!””

  51. In this awesome design of things you get a B- just for effort. Where you misplaced me ended up being on your facts. As it is said, details make or break the argument.. And that could not be much more accurate in this article. Having said that, let me reveal to you precisely what did deliver the results. Your authoring is definitely pretty convincing which is possibly the reason why I am taking an effort to opine. I do not make it a regular habit of doing that. Second, despite the fact that I can certainly notice the leaps in reason you make, I am not necessarily certain of exactly how you appear to connect the details which make the final result. For right now I will, no doubt yield to your point but hope in the future you actually connect the facts better.

  52. My spouse and I stumbled over here by a different web page and thought I might check things out. I like what I see so now i am following you. Look forward to looking over your web page again.

  53. Unquestionably believe that which you said. Your favorite justification appeared to be on the net the easiest thing to be aware of. I say to you, I definitely get annoyed while people think about worries that they plainly do not know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side effect , people can take a signal. Will probably be back to get more. Thanks

  54. After examine a few of the weblog posts on your web site now, and I really like your approach of blogging. I bookmarked it to my bookmark web site listing and will be checking back soon. Pls check out my web page as effectively and let me know what you think.

  55. Good post. I learn one thing more difficult on totally different blogs everyday. It should always be stimulating to learn content from other writers and practice a little bit one thing from their store. I’d want to use some with the content material on my weblog whether or not you don’t mind. Natually I’ll provide you with a hyperlink on your internet blog. Thanks for sharing.

  56. I feel that is one of the such a lot significant info for me. And i’m happy studying your article. However want to remark on few general things, The site taste is perfect, the articles is actually great : D. Excellent task, cheers

  57. There are certainly a lot of details like that to take into consideration. That is a great point to carry up. I offer the thoughts above as common inspiration but clearly there are questions like the one you bring up where an important thing can be working in trustworthy good faith. I don?t know if finest practices have emerged round issues like that, but I’m sure that your job is clearly identified as a fair game. Each boys and girls really feel the impact of just a second’s pleasure, for the rest of their lives.

  58. Good V I should certainly pronounce, impressed with your website. I had no trouble navigating through all the tabs and related information ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or something, website theme . a tones way for your client to communicate. Nice task..

  59. Hello! This is kind of off topic but I need some advice from an established blog. Is it difficult to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about setting up my own but I’m not sure where to start. Do you have any ideas or suggestions? Appreciate it

  60. Импортное оборудование для переработки пластика

    Сегодня человечество добывает гору жидких углеводородов, очень большая часть из них идет на выпуск пластмассовой тары, корпусов для электронных приборов и других изделий. Потом около двенадцати процентов производимых отходов составляет сложно деградирующий в природных условиях пластик, негативно влияющий на здоровье биосферы.

    Одним из самых новых предпринимательских трендов является переработка пластиковых отходов, с выработкой полезных и коммерчески привлекательных товаров: плитки для тротуара, долговечных покрытий для кровли и других полезных товаров. Наша фирма ПК «Полимерстрой18» предлагает купить специальное оборудование для переработки мусора в полезные материалы.

    Процесс переплавки отходов начинается с их нарезки до получения пластиковой массы, пригодной для дальнейшей температурной переработки и смешивания с минеральным наполнителем. Данная компания предлагает приобрести на российском рынке качественные измельчительные машины, модели их различаются в зависимости объёма перерабатываемого сырья.

    А затем гранулы нарезанного полимера спекаются с песком или другим наполнителем в разного рода металлических формах. В интернет-каталоге компании вы можете найти формы для производства плитки для тротуаров, полимерной черепицы, износоустойчивых водостоков. Также сейчас невероятно популярны произведённые по такой технологии декоративные заборчики. Различные изделия из полимерного композита могут использоваться также в энергетике, лёгкой промышленности и сельском хозяйстве.

    Важным элементом линии для производства песчано-полимерных композитов ещё станут смесители, которые формируют пригодную для запекания массу из 2 изначальных элементов. Качество и производительность такого рода машин могут быть разными, и потому вам стоит посмотреть на различные варианты на сайте, зайдя на страницу дробилка для пластика купить цена , переработка пластика в полезные для общества изделия может стать отличным вариантом заработка для тех, кто планирует избавить города от проблемы бесполезного мусора, попутно зарабатывая на этом.

    Также подобные машины найдут своё место рядом с предприятиями, в ходе работы которых образуется большой объем пластиковых отходов.

  61. Виртуальная Россия — ведущие направления работы проекта

    Интернет уже стал важной частью быта современного общества, особенно это касается любого бизнеса, потому как всё большее число людей в наше время ищет нужные услуги попросту в сети. Сайт «Виртуальная Россия» начинался как простая экономическая стратегия, которая позволяет спроецировать реальные модели предпринимательской деятельности в интернет мир. Сегодня ресурс стал очень популярной площадкой, которую навещают тысячи человек каждый день, суммарная аудитория зарегистрированных пользователей виртуальной страны превышает 100 тыс пользователей.

    Владельцы оффлайн бизнеса, предоставляющие такие услуги как бамбуковые шторы и гору других, могут использовать ресурс v-russia в роли инновационной рекламной площадки, где можно разместить полное описание оказываемых услуг, поставляемых товаров и получать из сети массу клиентов в реальный офис. Реальные кейсы показали довольно высокую привлекательность подобной рекламы при минимальных вложениях. Желающие разместить рекламу на сайте могут ознакомиться с ценами на странице «Реклама».

    Помимо функционала экономической стратегии, сайт играет роль настоящей социальной сети, благодаря огромному числу зарегистрированых предпринимателей. К примеру бизнес-форум нашего проекта служит превосходной обучающей площадкой для начинающих отечественных предпринимателей: тут вы можете познакомиться с разными вариантами ведения собственного дела в нашей стране, разместить уникальное коммерческое предложение и обсудить его с знающими людьми.

    Любителям проводить дни интересно, заодно зарабатывая денежки, мы советуем купить город в Виртуальной России и работать мэром. Трудясь над развитием своего города, завлекая в него немного больше жителей, вы быстро выведете своё владение на рентабельность.

    Финансы мэрам приносит реклама, что публикуется на страницах их городов хозяевами предприятий, сейчас на ресурсе приобретено уже 15 российских городов, три новых скоро будут закончены. С ходом развития функционала ресурса вы получите возможность продать пост мэра, получив солидные доходы за счет роста его цены.

    Присоединяйтесь к нам уже сейчас, будете гражданином нового, лучшего государства!

  62. Виртуальная Россия — все направления работы сайта

    Интернет давно стал важной частью повседневной жизни информационного общества, в особенности это касается локального торгового бизнеса, потому как всё большее число россиян сейчас ищет нужные товары и услуги просто в сети. Сайт «Виртуальная Россия» начинался как простая экономическая стратегия, которая позволяет перенести реальные модели предпринимательской деятельности в виртуальный мир. Сегодня ресурс стал сравнительно популярной online площадкой, которую навещают десятки тысяч человек каждый день, суммарная аудитория обитателей виртуальной федерации превышает сто тысяч пользователей.

    Владельцы реального бизнеса, предлагающие такие услуги как наращивание ресниц и большое число других, могут использовать сайт v-russia в роли необычной рекламной площадки, где можно оставить подробное описание предоставляемых услуг, поставляемых товаров и получать из Интернета массу клиентов в реальном офисе. Реальные кейсы демонстрируют сравнительно высокую рентабельность такого рода рекламы при небольших вложениях. Желающие оставить рекламу на портале могут познакомиться с прайсом на страничке «Реклама».

    Кроме функций экономической стратегии, сайт выполняет роль крайне полезной соцсети, благодаря огромному числу зарегистрированых пользователей. Например, бизнес-форум указанного проекта является превосходной обучающей площадкой для начинающих отечественных бизнесменов: тут вы сумеете ознакомиться с различными вариантами ведения своего дела в нашей стране, разместить ваше коммерческое предложение и обсудить его с знающими пользователями.

    Желающим проводить дни с интересом, попутно зарабатывая деньги, мы рекомендуем приобрести город в Виртуальной России и стать мэром. Поработав над прокачкой своего города, завлекая в него чуть больше жителей, вы постепенно выведете свое владение на прибыль.

    Деньги мэрам может приносить реклама, что публикуется на странице их городов представителями бизнеса, сегодня на портале приобретено уже 15 городов, три новых скоро будут достроены. С увеличением функционала портала вы сможете продать кресло мэра, получив солидные доходы за счёт увеличения его цены.

    Присоединитесь к нам уже сегодня, будете гражданином новой страны!

  63. If you wish to search nice dog, better to use web-links where you could do it. The best way to get a dog is to find photographs of puppy in the social networks. Cheap puppies for trading probable to find at web-sites. Many humanities all over the world use virtual serve and get dogs craiglist atlanta pets here.

    At 2puppies.com you can search inexpensive dogs for trading. Purchase a puppy online – it is very easy way. You can search photographs of dogs and connect with a seller. You can search your dog in USA less than $200. It is also possible to find a puppy with black stain. If you need to make warrant and to survey breed of a puppies, you should use manager serve. Specialists should search a cool for you and you will be very luck.

    Small puppies for commercial also are represented at web-site. There are many of methods to buy big dog. You can search Affenpinscher or Canaan dog. If you need to search and to purchase puppy, you can as well use serve at source. Administrators of the organization are published a lot of data. If you don’t know where to search places to sell dogs, you could ask specialists. They will help you.

    If you wish to have a small puppy, you should connect with managers and they help you. It is don’t hard method to find big dog. You should to make out that you should be very tender with your dog. Today you have many feasibilities to complete your home. At site you can also search a lot of stories about pets. At web-site you can also find data how better to search reasonable puppies. There are a lot of articles and interesting stories. You should as well search list of dogs.

    If you don’t know how to feed dogs, you should search different stories about it. It is probable to find data about different kind of food for puppies. You can also search articles about how better to prepare animals. If you don’t know cool facts about dogs, you could find it at web-site.

    Also needful to say that consultants of the organization will help you. If you have difficult questions, you have ability to communicate with administrators and ask them about help.

  64. “Hello there, just became aware of your blog through Google, and found that it is truly informative. I’m going to watch out for brussels. I will be grateful if you continue this in future. A lot of people will be benefited from your writing. Cheers!”

  65. “Hi there, just became aware of your blog through Google, and found that it is really informative. I am gonna watch out for brussels. I will be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!”

  66. Если вам нужны электромонтажные работы, вам потребуются услуги специалистов. Найти фирму, которая имеет шанс должным образом проложить кабель или оказать энергоаудит – тяжко. Хотя, если вы кликните получить ту на электроснабжение сюда, вам откроется безумное количество возможностей.

    На center-energo.com вы сможете подобрать сотрудников профильного уровня. Огромный опыт специалистов предоставляет шанс установить силовые трансформаторы или установить электрику в квартире. Если вам нужны услуги по настройке электрических счетчиков, то команда профессионалов сможет сделать работу в сжатые сроки. Если вам потребуется провести сети на территорию, специалисты имеют шанс сделать работу на протяжении пяти дней.

    Прокладка кабеля возможна как на частной территории, так и на территории офиса. Если необходим монтаж электропроводки, или замена кабелей – организация может сделать работу очень быстро. Нужны выделить и то, что вся работа выполняется опытными специалистами. Мастера фирмы используют только хорошие инструменты, а технологии у мастеров высокого класса.

    Подключение электричества к участку проводится невероятно быстро. Вы имеете возможность подключить электросети и настроить расчет использования электроэнергии по определенной мощности. Если нужна будет консультация по месту – менеджеры мгновенно проверят объект и предоставят важную информацию.

    Важно и то, что справку о всех тонкостях вы можете получить у специалистов. Менеджеры консультируют по всем вопросам, что значительно ускорит подключение сети к дому. Сегодня сетевые услуги выполняются специалистами моментально, хотя оговаривать период работ оптимальнее за пару недель.

    Услуги оказываются в столице, и все цены на сетевые работы в МО доступные, на чем необходимо акцентировать внимание!

  67. Hi Simran,

    I like the way you have written can you please write Program and also explain how we will run the program. Please do it that would be great help. Thanks

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.