ComputersProgramming

CSS Position: examples

. Novice make-up artists often experience difficulties in positioning elements via CSS . Position куда проще в освоении, чем кажется на первый взгляд. In fact, the CSS Position property is much easier to learn than it seems at first glance. Having mastered them, you get a powerful tool with which you can arrange all the elements of the page in the right places. добиться результата, нужно знать обо всех существующих значениях, поскольку принципы их действия сильно различаются But to achieve the result, you need to know about all the existing values, since the principles of their action are very different

Specificity of document flow construction

работает с потоком веб-страницы. Position CSS works with the stream of the web page. How can this be understood? html- разметке. By default, all the elements of the page are in the order in which you created them in the html- markup. header расположен над тегом footer, то и на странице он будет отображаться выше. If the header tag is located above the footer tag , it will also be displayed on the page above. footer в html над «хедером», «подвал» страницы будет отображаться над «шапкой». Conversely, if you decide to place a footer in html above the "header", the "basement" of the page will be displayed above the "header". In this case, the block elements occupy all the available width for them. The lower-case ones, in turn, are placed in one line until they occupy it all, and then they begin to be transferred to a new one. This order is called the "document flow".

To change the behavior of a stream, use the Position property . In CSS . float, но его мы рассматривать не будем. It can also change due to the float property , but we will not consider it. With the help of positioning, you can force the element to "fall out" from a normal thread, after which it will begin to behave in a new way. How exactly - depends on the used value of the property.

CSS Position: static

или статическое позиционирование, является значением по умолчанию для всех блоков html, которые вы создали. Position: static, or static positioning, is the default value for all the html blocks that you created. Under normal circumstances, you do not have to deal with it. static. If no positioning is specified for any block or row, then it has the value static. On the page, such a component is displayed in accordance with the flow. right/left или top/bottom, никакого эффекта не будет. If you specify the right / left or top / bottom properties , there will be no effect.

CSS Position: fixed

оказывается вне нормального потока документа. When using this property, the element is outside the normal flow of the document. относительно окна браузера, независимо от того, как размещаются прочие компоненты. Now its position is calculated relative to the browser window, regardless of how other components are placed. : fixed отправится в верхнюю часть страницы, прижмется к краю окна браузера, а прочие элементы займут его место в соответствии с потоком. In other words, the block with Position : fixed will go to the top of the page, press to the edge of the browser window, and other elements will take its place in accordance with the flow.

The main feature of fixedly positioned elements is that they can overlap other blocks and page lines. : fixed будет будто бы оставаться на месте, не исчезая с экрана. When scrolling, the block with Position : fixed will appear to stay in place, not disappearing from the screen. This is useful if you need to make a navigation or a similar element that a user should always have access to. Fixed positioning also applies if you want to place a quick scrolling button in a specific part of the page.

CSS Position: relative

. The use of this property is called relative positioning . : relative, тот останется на своем месте. If you set the Item to the Item : relative property, the item will remain in its place. right/left и top/bottom. At first glance, nothing much will happen, but everything will change if you additionally use the right / left and top / bottom properties . With their help, you can control the movement of a component relative to its location. останутся на своих положениях, не обращая внимания на освободившееся место . On the place where the block or line was before, there will be an empty space - other elements will remain at their positions, not paying attention to the vacant space .

When moving the component does not affect the position of the surrounding parts of the page. They will remain in their places, although a relatively positioned block can block them. The property itself is rarely used. Usually it is used in combination with the following option.

Absolute positioning

One of the most interesting and most frequently used options. When using the Position property absolute положение компонента страницы будет высчитываться относительно окна браузера. With the value absolute, the position of the page component will be calculated relative to the browser window. элементы (не являющиеся абсолютно позиционированными) словно «забудут» о существовании «собрата» с Position : absolute и займут его место в потоке. Other elements (not absolutely positioned) seem to "forget" about the existence of a "colleague" with Position : absolute and will take its place in the stream. : fixed, но есть и серьезные различия. It would seem that everything is exactly the same as in the case of Position : fixed, but there are also serious differences.

top/right/bottom/left. First, the position of the element can be freely controlled - it uses the top / right / bottom / left properties . bottom : 100px, блок «оттолкнется» от нижней част страницы на 100 пикселей. For example, if you set the bottom value to 100px, the block "pushes" from the bottom of the page to 100 pixels. Secondly, when scrolling, the "absolute" component will remain in its place, instead of moving with the page.

Interaction of absolute blocks with parent elements

You can achieve even more precise control over the absolutely positioned component. : fixed, relative или absolute. To do this, you must set its parent to the Position : fixed, relative, or absolute property .

Let's consider an example. div с классом relative-div, внутри которого размещается div с классом absolute-div. You have a div with the relative-div class , inside of which is a div with the class absolute-div. : absolute. Set the Position : absolute property to the inner block . That immediately "flies" out of the stream and it turns out somewhere above, because now its location is calculated relative to the browser window. relative-div свойство Position : relative и «блудный сын» возвращается на место. Now we assign the Position -relative property to the block with the relative-div class and the "prodigal son" returns to its place. Nearly. In fact, it is in the upper left corner of the parent element.

Why is this happening? : absolute. The point is in the specificity of the Position : absolute property . static, позиция начинает зависеть от родительского элемента. By default its position depends on the browser window, but if the "parent" is also positioned as something other than static, the position begins to depend on the parent element. This is very convenient, because you can place the component anywhere, without calculating huge numbers relative to the browser window. Reception is often used to place icons, buttons and other small items.

Position CSS in the center

One of the main difficulties for beginners is to center the element vertically and horizontally. , сделать это проще простого. Using the Position property wisely , it's easy to do. CSS Position: absolute in the center is set as follows. iv с классом absolute-div, который находится в «диве» с классом relative-div. Suppose you have a d iv with the absolute-div class , which is in the "diva" with the relative-div class . "Parent" is positioned relatively and its width is equal to the width of the entire page. и высоту 400 px, абсолютное позиционирование и по умолчанию располагается в верхнем левом углу родительского элемента. The "descendant" has a width and height of 400 px, absolute positioning and by default is located in the upper left corner of the parent element.

top: 50 % и left: 50 %. All you need to do is set the absolute component top: 50% and left: 50%. Almost done! сдвинулся с места и оказался почти в центре, но не совсем. Absolute-div moved from the spot and was almost in the center, but not quite. The middle of the "parent" touches its edge, and we need the center of the "descendant" to be in the center of the block. margin-left и margin-right со значениями -200 px. To do this, you need to set it to margin-left and margin-right with the values of -200 px. This way we will move the absolutely positioned block to half its height and width. Everything, he is in the center!

Overlapping components

The problem may be a difficult, at first glance, "overlap" of positioned elements on their "neighbors". : fixed будет перекрывать все, что расположено на странице. For example, a component with Position : fixed will overlap everything on the page. z-index, однако помните, что оно работает только для позиционированных элементов. You can correct the situation using the z-index property , but remember that it only works for positioned elements. Accordingly, if you want to place a block on a fixedly positioned element, this block will also have to be positioned. For example, relative.

учший способ освоить позиционирование – рассматривать примеры Position CSS, экспериментировать и пробовать что-то свое. L uchshy way to master positioning - to consider examples of Position CSS, to experiment and try something your own. calc() – это даст возможность более гибко настраивать расположение. Try to learn how to use it in combination with the calc () function - this will allow you to more flexibly adjust the location. However, remember that this property is not intended to build the entire "grid" of the page. With its help you need to move relatively small elements, otherwise you can too easily get confused.

Similar articles

 

 

 

 

Trending Now

 

 

 

 

Newest

Copyright © 2018 en.delachieve.com. Theme powered by WordPress.