Css див над дивом

Как с помощью CSS наложить элементы друг на друга

При разработке веб-дизайна часто нужно сделать так, чтобы два элемента перекрывались или полностью накладывались друг на друга. В CSS это можно реализовать с помощью свойства position и Grid.

Способ 1. Использование свойства Position

Свойство position со значением absolute разместит абсолютно позиционированный элемент на странице. В этом случае указывается позиция элемента относительно левого верхнего угла веб-страницы.

При добавлении других элементов первый будет смещаться вниз. Это можно исправить, установив для родительского элемента position: relative. Тогда все дочерние элементы с position: absolute будут размещены абсолютно относительно верхнего угла родительского элемента.

Также этот подход можно использовать для размещения одного элемента поверх другого. Например, два дочерних элемента, расположенных друг над другом, один из которых будет смещен на 150 пикселей. Они располагаются в одном родительском элементе и остаются внутри него.

Parent

Child 1

Child 2

.child < position: absolute; top: 0; >.child-1 < left: 0; >.child-2 < left: 150px; >.parent

Способ 2. Использование CSS Grid

Еще одним способом наложения элементов друг на друга является использование CSS Grid. Но эта технология поддерживается не всеми старыми браузерами.

С помощью Grid мы можем разместить элемент внутри контейнера следующим образом:

И если один элемент должен накладываться на другой, то нужно поместить их в одну область сетки. Давайте также немного сместим элемент, используя отступ.

Для облегчения позиционирования я создал CSS Grid Generator , который поможет вам визуально сконструировать необходимый макет.

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

Источник

How to overlay one div over another div

I need assistance with overlaying one individual div over another individual div . My code looks like this:

Unfortunately I cannot nest the div#infoi or the img , inside the first div.navi . It has to be two separate div s as shown, but I need to know how I could place the div#infoi over the div.navi and to the right most side and centered on top of the div.navi .

Not the case in this question but if you have one div inside another div the inner div may be fully or partially masked due to overflow: hidden , use overflow: visible instead.

9 Answers 9

#container < width: 100px; height: 100px; position: relative; >#navi, #infoi < width: 100%; height: 100%; position: absolute; top: 0; left: 0; >#infoi
 
a
b

I would suggest learning about position: relative and child elements with position: absolute .

thanks alex for your help but what I am finding now is that when I resize my window and drag it to be smaller, my info image is not staying with it’s parent div. Basically want it to move with the parent div and stay pretty much at the same position even though the screen has been resized somewhat.

@tonsils: The instructions by alex should give you the desired result, so there must be something else causing the problem you describe. Could you provide us with a sample of the code (HTML + CSS) so we can help you?

absolute ly positioned elements are positioned relative to their nearest explicitly positioned ( position:absolute|relative|fixed ) parent element. just further clarification . jsfiddle.net/p5jkc8gz

Depending on the case, this can be adapted. In my situation I didn’t need #navi to be top:0 left:0, and as a general case If you are having HTML code, it’s going to be situated as long as the HTML tree is parsed. So maybe in this case that definition is not necessary.

Adding the in z-index:10; resolved the issue I was having with the textarea being uneditable when other textarea’s was not visible. Thank you, Alex.

The accepted solution works great, but IMO lacks an explanation as to why it works. The example below is boiled down to the basics and separates the important CSS from the non-relevant styling CSS. As a bonus, I’ve also included a detailed explanation of how CSS positioning works.

TLDR; if you only want the code, scroll down to The Result.

The Problem

There are two separate, sibling, elements and the goal is to position the second element (with an id of infoi ), so it appears within the previous element (the one with a class of navi ). The HTML structure cannot be changed.

Proposed Solution

To achieve the desired result we’re going to move, or position, the second element, which we’ll call #infoi so it appears within the first element, which we’ll call .navi . Specifically, we want #infoi to be positioned in the top-right corner of .navi .

CSS Position Required Knowledge

CSS has several properties for positioning elements. By default, all elements are position: static . This means the element will be positioned according to its order in the HTML structure, with few exceptions.

The other position values are relative , absolute , sticky , and fixed . By setting an element’s position to one of these other values it’s now possible to use a combination of the following four properties to position the element:

In other words, by setting position: absolute , we can add top: 100px to position the element 100 pixels from the top of the page. Conversely, if we set bottom: 100px the element would be positioned 100 pixels from the bottom of the page.

Here’s where many CSS newcomers get lost — position: absolute has a frame of reference. In the example above, the frame of reference is the body element. position: absolute with top: 100px means the element is positioned 100 pixels from the top of the body element.

The position frame of reference, or position context, can be altered by setting the position of a parent element to any value other than position: static . That is, we can create a new position context by giving a parent element:

For example, if a element is given position: relative , any child elements use the as their position context. If a child element were given position: absolute and top: 100px , the element would be positioned 100 pixels from the top of the element, because the is now the position context.

The other factor to be aware of is stack order — or how elements are stacked in the z-direction. The must-know here is the stack order of elements are, by default, defined by the reverse of their order in the HTML structure. Consider the following example:

In this example, if the two

elements were positioned in the same place on the page, the
Top

element would cover the

Bottom

element. Since

Top

comes after

Bottom

in the HTML structure it has a higher stacking order.

The stacking order can be changed with CSS using the z-index or order properties.

We can ignore the stacking order in this issue as the natural HTML structure of the elements means the element we want to appear on top comes after the other element.

So, back to the problem at hand — we’ll use position context to solve this issue.

The Solution

As stated above, our goal is to position the #infoi element so it appears within the .navi element. To do this, we’ll wrap the .navi and #infoi elements in a new element so we can create a new position context.

Then create a new position context by giving .wrapper a position: relative .

With this new position context, we can position #infoi within .wrapper . First, give #infoi a position: absolute , allowing us to position #infoi absolutely in .wrapper .

Then add top: 0 and right: 0 to position the #infoi element in the top-right corner. Remember, because the #infoi element is using .wrapper as its position context, it will be in the top-right of the .wrapper element.

Because .wrapper is merely a container for .navi , positioning #infoi in the top-right corner of .wrapper gives the effect of being positioned in the top-right corner of .navi .

And there we have it, #infoi now appears to be in the top-right corner of .navi .

The Result

The example below is boiled down to the basics, and contains some minimal styling.

/* * position: relative gives a new position context */ .wrapper < position: relative; >/* * The .navi properties are for styling only * These properties can be changed or removed */ .navi < background-color: #eaeaea; height: 40px; >/* * Position the #infoi element in the top-right * of the .wrapper element */ #infoi < position: absolute; top: 0; right: 0; /* * Styling only, the below can be changed or removed * depending on your use case */ height: 20px; padding: 10px 10px; >
 

An Alternate (Grid) Solution

Here’s an alternate solution using CSS Grid to position the .navi element with the #infoi element in the far right. I’ve used the verbose grid properties to make it as clear as possible.

:root < --columns: 12; >/* * Setup the wrapper as a Grid element, with 12 columns, 1 row */ .wrapper < display: grid; grid-template-columns: repeat(var(--columns), 1fr); grid-template-rows: 40px; >/* * Position the .navi element to span all columns */ .navi < grid-column-start: 1; grid-column-end: span var(--columns); grid-row-start: 1; grid-row-end: 2; /* * Styling only, the below can be changed or removed * depending on your use case */ background-color: #eaeaea; >/* * Position the #infoi element in the last column, and center it */ #infoi
 

An Alternate (No Wrapper) Solution

In the case we can’t edit any HTML, meaning we can’t add a wrapper element, we can still achieve the desired effect.

Instead of using position: absolute on the #infoi element, we’ll use position: relative . This allows us to reposition the #infoi element from its default position below the .navi element. With position: relative we can use a negative top value to move it up from its default position, and a left value of 100% minus a few pixels, using left: calc(100% — 52px) , to position it near the right-side.

/* * The .navi properties are for styling only * These properties can be changed or removed */ .navi < background-color: #eaeaea; height: 40px; width: 100%; >/* * Position the #infoi element in the top-right * of the .wrapper element */ #infoi < position: relative; display: inline-block; top: -40px; left: calc(100% - 52px); /* * Styling only, the below can be changed or removed * depending on your use case */ height: 20px; padding: 10px 10px; >
  

Источник

Overlay Divs Without Absolute Position

What follows is a long explanation, but it’s the only way to effectively communicate the issue I’m trying to resolve. I am (somewhat desperately, and entirely unsuccessfully) trying to overlay divs without the use of absolute positioning. The need stems from a paypal cart that I place on the site via a Javascript. The cart’s natural position is hard against the top margin of the webpage (not its containing div, which is #wpPayPal, or the wrapper for this div, #main). The script’s author strongly recommends against customizing the cart’s stylesheet, but I found a tutorial he wrote that enables insertion of the cart into a placeholder div, with positioning instructions for the container that works — I was able to position the cart below the site’s top banner section. However. The cart’s HTML form and a ul element within each have height requirements in the cart’s stylesheet, and this pushes the page’s main content, wrapped by the container div #imageWrapper, too far down the page to be acceptable. I tried to position #imageWrapper over #main with several ideas gathered from posts on this site with no success. I’ve tried absolute positioning on #imageWrapper, but this frees the footer to float beneath. #imageWrapper’s height is variable, hence I do not want to hold the footer in place with height, since the min-height to prevent overlap would push the footer down too far for much of the site’s content. I also tried pulling position:relative from the cart form’s CSS, but the cart immediately floats back to the top of the webpage. Margin, top-margin, etc.,do not remedy this. I then read an article on using position:relative and z-index to overlay divs. Tried this, too, first by putting z-index: -1 on #main (the div that wraps the paypal cart), but the cart disappears. Not sure where it goes, either, since the site’s breadcrumb nav, also wrapped by #main, stayed put. I then set the z-index for main to 0 and applied position:relative to #imageWrapper with z-index:100. The cart reappeared but still holds #imageWrapper down. Suggestions are greatly welcomed. I’m not an interface person by any stretch of the imagination, just a guy who knows how to use Google, so thanks in advance for clearly articulating your resolution 🙂 Also, FYI, presently I have the min-height requirement for the cart form set to 0, and set the UL element within to height:auto. With only a single item in the cart, this allows #imageWrapper to move up the page enough to be acceptable, but this is not a viable long-term solution. Here’s an example page — to see the cart, add an item using the dropdown that appears below the main image. In its expanded state, you’ll see how #imageWrapper sits against it. I’ve included portions of the offending HTML / CSS below:

#main < display: inline; position: relative; z-index: 0; >#imageWrapper < clear: both; width: 840px; margin: 0 auto; padding: 0; position: relative; z-index: 100; >#imageInnerWrapper < width: 840px; margin: 0 auto; padding: 0; position: relative; z-index: 100; >#featureImage < width: 840px; margin: 0 auto; padding: 0; >#wpPayPal < overflow: hidden; float: right; margin-right: 100px; min-width: 365px; min-height: 20px; >/* Override the default Mini Cart styles */ #wpBody #PPMiniCart form < position: relative; right: auto; width: auto; min-height: 0; >#wpBody #PPMiniCart form ul

7 Answers 7

You can do it with grid also :

Источник

Читайте также:  в части страницы.
Оцените статью