Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> CSS

CSS से इमेज पर टेक्स्ट को सेंटर में पोज़िशन करें

इमेज के ठीक केंद्र में टेक्स्ट रखने के लिए position: absolute के साथ transform: translate(-50%, -50%) तकनीक का उपयोग करें। यह किसी भी आकार के टेक्स्ट/इमेज के लिए काम करता है।

उदाहरण: इमेज पर केंद्रित टेक्स्ट

<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      position: relative;
      display: inline-block;
      max-width: 100%;
    }
    img {
      width: 100%;
      height: auto;
      opacity: 0.3;
      display: block;
    }
    .centered-text {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 18px;
      color: white;
      background: rgba(0,0,0,0.7);
      padding: 10px 20px;
      border-radius: 5px;
      white-space: nowrap;
    }
  </style>
</head>
<body>
  <h2>इमेज टेक्स्ट</h2>
  <p>इमेज के केंद्र में टेक्स्ट जोड़ें:</p>
  <div class="container">
    <img src="trolltunga.jpg" alt="Norway" width="1000" height="300">
    <div class="centered-text">केंद्र</div>
  </div>
</body>
</html>

क्यों transform: translate(-50%, -50%)?

  1. top: 50%; left: 50% → एलिमेंट के **टॉप-लेफ्ट कोने** को कंटेनर के केंद्र पर रखता है
  2. translate(-50%, -50%) → एलिमेंट को अपने **आधे आकार** से ऊपर-बाएं खींचता है
  3. परिणाम: एलिमेंट का **केंद्र** = कंटेनर का **केंद्र**

मॉडर्न विकल्प: Flexbox/Grid

/* Flexbox - सबसे सरल */
.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Grid - सबसे सरल */
.container {
  display: grid;
  place-items: center;
}

/* दोनों में चाइल्ड स्वचालित केंद्रित होता है */
img { width: 100%; height: auto; }

तुलना

विधिब्राउज़र सपोर्टजटिलतारिस्पॉन्सिव
absolute + transformसभी (IE9+)मध्यमहां
Flexboxसभी (IE10+)सरलहां
Grid place-itemsमॉडर्नसबसे सरलहां
  1. CSS से इमेज पर बटन कैसे जोड़ें? CSS से इमेज पर बटन कैसे जोड़ें?

    CSS से इमेज पर बटन जोड़ने का कोड निम्नलिखित है:उदाहरण<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> img{    width: 100%; } div {    position: relative;    width

  1. CSS से टेक्स्ट बटन कैसे स्टाइल करें? CSS से टेक्स्ट बटन कैसे स्टाइल करें?

    CSS का उपयोग करके विभिन्न रंगों और शैलियों के टेक्स्ट बटन बनाए जा सकते हैं। इस उदाहरण में पांच अलग-अलग प्रकार के बटन (Success, Info, Warning, Danger, Default) दिखाए गए हैं जिनमें होवर इफेक्ट भी शामिल है। उदाहरण <!DOCTYPE html> <html> <head> <meta name=viewport content=width=

  1. CSS से ग्लोइंग टेक्स्ट कैसे बनाएं? CSS से ग्लोइंग टेक्स्ट कैसे बनाएं?

    CSS से ग्लोइंग टेक्स्ट बनाने के लिए, कोड निम्नानुसार है -उदाहरण<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style>    body {       background-color: rgb(0, 0, 0);