इमेज के ठीक केंद्र में बटन रखने के लिए position: absolute के साथ transform: translate(-50%, -50%) तकनीक का उपयोग करें। यह सबसे विश्वसनीय सेंटरिंग विधि है।
उदाहरण: इमेज के केंद्र में बटन
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: relative;
width: 100%;
max-width: 250px;
}
.box img {
width: 100%;
height: auto;
display: block;
}
.box .btn {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 12px 24px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
white-space: nowrap;
}
.box .btn:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="box">
<img src="https://www.tutorialspoint.com/videotutorials/images/current_affairs_home.jpg" alt="Current Affairs">
<button class="btn">बटन</button>
</div>
</body>
</html>
क्यों transform: translate(-50%, -50%)?
top: 50%; left: 50%एलिमेंट के टॉप-लेफ्ट कोने को केंद्र में रखता हैtranslate(-50%, -50%)एलिमेंट को अपने आकार के आधे से पीछे खींचता है- परिणाम: एलिमेंट का **केंद्र** कंटेनर के केंद्र में होता है
- यह किसी भी आकार के एलिमेंट के लिए काम करता है
अन्य पोज़िशनिंग तकनीकें
/* Flexbox से सेंटरिंग (मॉडर्न) */
.box {
display: flex;
justify-content: center;
align-items: center;
}
/* Grid से सेंटरिंग */
.box {
display: grid;
place-items: center;
}