CSS - 始终显示中心图像

时间:2016-06-10 11:19:41

标签: html css image center

我有一张我在Div中使用的图片。

我想知道如何在任何时候垂直和水平居中放置图像。

此刻,当我伸展它时,它似乎从左上角延伸,是否有一种方法可以让它始终居中。

我在网上搜索并尝试了各种各样的东西,但似乎无法让它发挥作用。

这是我的HTML:

    public void saveArrayList(ArrayList aList, String s) {
    SharedPreferences sharedPrefs = getSharedPreferences(prefs, MODE_PRIVATE);
    editor = sharedPrefs.edit();

    Gson gson = new Gson();
    String json = gson.toJson(aList);

    editor.putString(s, json);
    editor.commit();
}

public void loadFloatList(ArrayList aList, String s) {
    SharedPreferences sharedPrefs = getSharedPreferences(prefs, MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPrefs.getString(s, null);
    Type type = new TypeToken<ArrayList<Float>>() {
    }.getType();
    aList = gson.fromJson(json, type);
}

这是我的css:

import sys, argparse, csv
import numpy as np

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt

def open_file(file_name, mode):
    """Open a file."""
    try:
        with open(sys.argv[1], 'r') as the_file:
          filename=the_file.read()

    except IOError as err:
        print("Unable to open the file", file_name, "Ending program.\n", err)
        input("\n\nPress the enter key to exit.")
        sys.exit()
    else:
        return filename

"""Cities.txt file as an argument"""     
try:
   my_file = open_file(sys.argv[1], 'r')
except:
   print("GDD needs one argument", "\nEnding program...\n")
   input("Press the enter key to exit.")
   sys.exit()


extension=".csv"
for line in my_file.splitlines():
    file_name=line+extension
    print(file_name) 
    with open('data/'+ file_name, "rU") as files:
        val = list(csv.DictReader(files))  
        l = []
    for i in range(0, len(val)):
        row = val[i]
        if row['Min Temp'] == '' or row['Max Temp'] == '':
                pass 
        else:
            GDD = ((float(row['Min Temp']) + float(row['Max Temp']))/2)-10
            l.append(GDD)

            val[i]['GDD'] = GDD

            #print(row['Min Temp'], ' ' , row['Max Temp'], ' ',    str(round(row['GDD'], 2)))

            #plt.subplot(1,1,1)        
            #x = np.linspace(1, 12, 365, endpoint=True)


    x = np.linspace(1, 12, 365, endpoint=True)
    plt.plot(x,GDD, label = file_name.split(',')[0])
    plt.gcf().autofmt_xdate()
    plt.legend(loc="upper left")

    plt.xlabel('Months', color='black')
    plt.ylabel('Cumulative GDD (>10°C)')
    plt.title('Accumulated Growing Degree Days')
    plt.draw()        

感谢您的任何帮助或建议,谢谢您。

  

编辑你可以看到,当我拉伸浏览器时,它   似乎是从左边伸展,我希望能够拥有   图像居中,所以它从各个方向均匀延伸*

4 个答案:

答案 0 :(得分:3)

我得到了解决方案..!

这是你的html文件:

<div class="container"></div>

CSS文件:

.container {
width: 100%;
height: 75vh;
position: absolute;
margin: auto;
background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
background-size: cover;
background-repeat: no-repeat;
background-position: 50% 50%;
top: 0;
left: 0;}

这是有效的demo

答案 1 :(得分:1)

background-position: center会将您的图像在垂直和水平中心对齐。

检查以下代码段:

* {
  margin: 0;
  padding: 0;
}
.container {
  width: 100%;
  height: 100vh;
  background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
  background-repeat: no-repeat;
  background-position: center;
}
<div class="container"></div>

答案 2 :(得分:1)

&#13;
&#13;
.container {
    width: 100%;
    height: 75vh;
    background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
  background-size:auto;
}
&#13;
<div class="container"></div>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

HTML:

<div class="container"></div>

CSS:

.container{width: 100%;height: 75vh;position: absolute;margin: auto;background-image: url("http://i.stack.imgur.com/2OrtT.jpg");background-size: cover;background-repeat: no-repeat;background-position: 50% 50%;top: 0;left: 0;}