Added solution to Lock an Element to the Browser Window with Fixed Positioning (#34318)

* Update index.md

* Update index.md
This commit is contained in:
The Coding Aviator
2019-03-09 19:33:18 +05:30
committed by Randell Dawson
parent 4c4b7cc2cf
commit 2d07699cd6

View File

@ -1,10 +1,66 @@
---
title: Lock an Element to the Browser Window with Fixed Positioning
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
## Lock an Element to the Browser Window with Fixed Positioning
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/responsive-web-design/applied-visual-design/lock-an-element-to-the-browser-window-with-fixed-positioning/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
Use `position: fixed;`.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
Use the `left` and `top` properties.
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
```html
<style>
#navbar {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
background-color: #767676;
}
nav ul {
margin: 0px;
padding: 5px 0px 5px 30px;
}
nav li {
display: inline;
margin-right: 20px;
}
a {
text-decoration: none;
}
</style>
<body>
<header>
<h1>Welcome!</h1>
<nav id="navbar">
<ul>
<li><a href="">Home</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
</header>
<p>I shift up when the #navbar is fixed to the browser window.</p>
</body>
```
### Code Explanation:
* `#navbar{}` selects all the elements with the ID of `navbar`.
* `position: fixed;` positions the element with respect to the viewport i.e. the output screen in this case.
* `top: 0px;` and `right: 0px;` offsets the element by `0px` to the top and left respectively and it is placed in the top-left corner of the screen.