यह मुख्य रूप से CSS का काम है। JavaScript की आवश्यकता नहीं। CSS Flexbox (flex-direction: column-reverse) या Grid का उपयोग करके एलिमेंट्स का क्रम बदलें।
CSS Flexbox समाधान (सबसे सरल)
<style>
.container {
display: flex;
flex-direction: column-reverse; /* क्रम उलट दें */
gap: 10px;
}
</style>
<div class="container">
<div class="demo1">DIV_DEMO1 (पहला HTML में)</div>
<div class="demo2">DIV_DEMO2 (दूसरा HTML में)</div>
</div>
/* विज़ुअल क्रम: DEMO2 ऊपर, DEMO1 नीचे */
CSS Grid समाधान
<style>
.container {
display: grid;
grid-template-rows: auto auto;
}
.demo1 { grid-row: 2; } /* दूसरी पंक्ति में */
.demo2 { grid-row: 1; } /* पहली पंक्ति में */
</style>
JavaScript से डायनामिकली क्रम बदलें
<div id="container">
<div class="box" id="box1">बॉक्स 1</div>
<div class="box" id="box2">बॉक्स 2</div>
<div class="box" id="box3">बॉक्स 3</div>
</div>
<button onclick="reverseOrder()">क्रम उलटें</button>
<button onclick="moveToTop('box3')">बॉक्स 3 को ऊपर ले जाएं</button>
<script>
function reverseOrder() {
const container = document.getElementById('container');
// बच्चों को उलटें और पुनः जोड़ें
[...container.children].reverse().forEach(child => container.appendChild(child));
}
function moveToTop(boxId) {
const container = document.getElementById('container');
const box = document.getElementById(boxId);
container.insertBefore(box, container.firstChild);
}
</script>
CSS position: relative/absolute (ओवरलैपिंग के लिए)
<style>
.parent { position: relative; height: 200px; }
.child {
position: absolute;
top: 50px; left: 50px; /* पैरेंट के सापेक्ष */
}
</style>
<div class="parent">
<div class="child">मैं पैरेंट के सापेक्ष 50px, 50px पर हूँ</div>
</div>
JavaScript से पोजीशन गणना करें
function positionRelativeTo(target, reference) {
const targetRect = target.getBoundingClientRect();
const refRect = reference.getBoundingClientRect();
// रेफरेंस के सापेक्ष स्थिति
const relativeTop = targetRect.top - refRect.top;
const relativeLeft = targetRect.left - refRect.left;
return { top: relativeTop, left: relativeLeft };
}
// उपयोग
const box1 = document.getElementById('box1');
const box2 = document.getElementById('box2');
const pos = positionRelativeTo(box2, box1);
console.log(`बॉक्स2 बॉक्स1 से ${pos.top}px नीचे, ${pos.left}px दाएं है`);
चलाने का तरीका
HTML फ़ाइल में CSS/JS शामिल करके ब्राउज़र में खोलें।
सारांश
| आवश्यकता | समाधान |
|---|---|
| क्रम उलटें | CSS: flex-direction: column-reverse |
| कस्टम क्रम | CSS: order प्रॉपर्टी (Flex/Grid) |
| डायनामिक पुनः क्रम | JS: appendChild(), insertBefore() |
| ओवरलैपिंग पोजीशन | CSS: position: absolute पैरेंट में relative |
| पोजीशन गणना | JS: getBoundingClientRect() |