id="infoi"> src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>
Выполнить фрагмент кода Скрыть результаты
Альтернативное (сеточное) решение
Вот альтернативное решение с использованием CSS Grid для позиционирования .navi элемента с #infoi элементом справа. Я использовал подробные grid свойства, чтобы сделать его максимально понятным.
: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 grid-column-start: var(--columns); grid-column-end: span 1; grid-row-start: 1; place-self: center; >
class="wrapper"> class="navi">
id="infoi"> src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>
Выполнить фрагмент кода Скрыть результаты
Альтернативное (без обертки) решение
В случае, если мы не можем редактировать HTML, то есть мы не можем добавить элемент-обертку, мы все равно можем добиться желаемого эффекта.
Вместо того , чтобы использовать position: absolute на #infoi элементе, мы будем использовать position: relative . Это позволяет нам переместить #infoi элемент из его позиции по умолчанию под .navi элементом. С помощью position: relative мы можем использовать отрицательное top значение, чтобы переместить его из положения по умолчанию, и left значение 100% минус несколько пикселей, используя left: calc(100% — 52px) , чтобы расположить его рядом с правой стороной.
/* * 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; >
class="navi">
id="infoi"> src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>
Выполнить фрагмент кода Скрыть результаты
это самая полезная запись IMO, потому что она объясняет, почему она работает!
Это, вероятно, лучшее объяснение того, как работает позиционирование, которое я видел до сих пор. Краткий, но достаточно глубокий, чтобы понять это правильно.
Так же по качеству ответа. Ясное объяснение, которое я видел.
Это отличный ответ, особенно для новичков в css
Престижность для объяснения
Используя div стиль z-index:1; и position: absolute; вы можете наложить div на любой другой div .
z-index определяет порядок, в котором div’ы укладываются. Div с более высоким z-index появится перед div с более низким z-index . Обратите внимание, что это свойство работает только с позиционированными элементами .
Можете ли вы привести пример?
Примечание о позиционировании элементов имеет решающее значение.
Этот ответ настолько неполный, что ему нужен целый пост, чтобы объяснить, почему. Посмотрите контексты укладки.
Новая спецификация Grid CSS обеспечивает гораздо более элегантное решение. Использование position: absolute может привести к перекрытию или масштабированию, в то время как Grid избавит вас от грязных хаков CSS.
Самый минимальный пример Grid Overlay:
class="container"> class="content">This is the content class="overlay">Overlay - must be placed under content in the HTML
.container display: grid; > .content, .overlay grid-area: 1 / 1; >
Вот и все. Если вы не строите для Internet Explorer, ваш код, скорее всего, будет работать.
Это должно быть лучшим ответом.
Превосходный ответ. Выбранный ответ должен быть переоценен.
Идеальное решение
Здесь следует простое решение на 100% на основе CSS. «Секрет» заключается в использовании display: inline-block элемента в оболочке. Изображение vertical-align: bottom на картинке — это хак для преодоления отступов в 4 пикселя, которые некоторые браузеры добавляют после элемента.
Совет : если элемент перед упаковщиком встроен, он может оказаться вложенным. В этом случае вы можете «обернуть обертку» внутри контейнера, display: block обычно старого и доброго div .
.wrapper display: inline-block; position: relative; > .hover position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 188, 212, 0); transition: background-color 0.5s; > .hover:hover background-color: rgba(0, 188, 212, 0.8); // You can tweak with other background properties too (ie: background-image). > img vertical-align: bottom; >
class="wrapper"> class="hover">
src="http://placehold.it/450x250" />
Выполнить фрагмент кода Скрыть результаты
Это то, что вам нужно:
function showFrontLayer() document.getElementById('bg_mask').style.visibility='visible'; document.getElementById('frontlayer').style.visibility='visible'; > function hideFrontLayer() document.getElementById('bg_mask').style.visibility='hidden'; document.getElementById('frontlayer').style.visibility='hidden'; >
#bg_mask position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; margin-top: 0px; width: 981px; height: 610px; background : url("img_dot_white.jpg") center; z-index: 0; visibility: hidden; > #frontlayer position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: 70px 140px 175px 140px; padding : 30px; width: 700px; height: 400px; background-color: orange; visibility: hidden; border: 1px solid black; z-index: 1; > style>
HTTP-EQUIV="EXPIRES" CONTENT="-1" /> action="test.html"> id="baselayer"> type="text" value="testing text"/> type="button" value="Show front layer" onclick="showFrontLayer();"/> Click 'Show front layer' button
Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing textsting text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text id="bg_mask"> id="frontlayer">
Now try to click on "Show front layer" button or the text box. It is not active.
Use position: absolute to get the one div on top of another div.
The bg_mask div is between baselayer and front layer.
In bg_mask, img_dot_white.jpg(1 pixel in width and height) is used as background image to avoid IE browser transparency issue;
type="button" value="Hide front layer" onclick="hideFrontLayer();"/>
Выполнить фрагмент кода Скрыть результаты
Я не большой программист и не эксперт в CSS, но я все еще использую вашу идею в своих веб-проектах. Я пробовал разные разрешения тоже:
#wrapper margin: 0 auto; width: 901px; height: 100%; background-color: #f7f7f7; background-image: url(images/wrapperback.gif); color: #000; > #header float: left; width: 100.00%; height: 122px; background-color: #00314e; background-image: url(images/header.jpg); color: #fff; > #menu float: left; padding-top: 20px; margin-left: 495px; width: 390px; color: #f1f1f1; >
id="wrapper"> id="header"> id="menu"> menu will go here
Выполнить фрагмент кода Скрыть результаты
Конечно, вокруг них будет обертка. Вы можете управлять расположением меню div, которое будет отображаться внутри заголовка div с левыми полями и верхними позициями. Вы также можете настроить меню div, если хотите.