如何在图像上放置文字?

时间:2019-02-01 23:01:41

标签: html css

我正在尝试在图像上放置一些文本并将其居中。我环顾四周,看到的代码不适合我。谁能帮助我找出问题所在?

.image img  {
    width: 100%;
    height: 300px;
    position: relative;
    padding: 15px 5px 10px 5px;
    
}

.image h1 {
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
font-weight: 800;
color: black;
text-transform: uppercase;
transform: 50%;
font-size: 2rem;
position: absolute;
}

.image p {
    font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
    font-weight: 400;
    color: black;
    text-transform: uppercase;
    position: absolute;
    top: 50%;
    left: 50%;
    font-size: 1rem;

    
    }
<div class="image">
        <img src="grass.jpg"></img>
<h1>Big Cats Lawn Service </h1>
<p>Let the big cat tame your jungle</p>

</div>

抱歉,如果这是一个愚蠢的问题,我正在尝试自学。我在Mac OS Mojave上使用带有实时服务器的Visual Studio Code(如果有任何区别)。

2 个答案:

答案 0 :(得分:0)

HTML:

using System;
using System.Collections.Generic;


public class Program
{
    static List<string> _zipCodes;

    static Program()
    {
        _zipCodes = new List<string>() { "80205", "80225", "80210" };
    }

    static void Main(string[] args)
    {
        string userZip = string.Empty;

        do
        {
            Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area.");
            Console.WriteLine();
            Console.WriteLine("Enter a -1 to exit the program");
            userZip = Console.ReadLine();

            if (_zipCodes.Contains(userZip))//<---------------THAT WAY
            {
                 Console.WriteLine("We support zip code {0}", userZip); ;
            }
            else
            {
                Console.WriteLine("We do not support zip code {0}", userZip);
            }

        } while (userZip != "-1");

    }
}

CSS:

<div class="container">
  <img src="image.jpg" alt="image">
  <div class="center">center</div>
</div>

来源:W3schools

答案 1 :(得分:0)

您可以使用z-index属性来确保文本始终位于图像上方

您可以使用text-align将文本居中

代码:

.container {
  position: relative;
  text-align: center;
  color: white;
}

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}