css 如何使背景图像的全高和相对居中

jrcvhitl  于 2023-03-20  发布在  其他
关注(0)|答案(2)|浏览(184)

我有一个背景图像与一些文字在上面。

正如你所看到的,图像在70 px左右被截断了,我可以把section或main的高度改为700 px,然后显示完整的背景图像,但是背景不会对页面宽度做出响应。
我希望显示背景图像的完整高度,如下所示:

但我也希望图像总是以屏幕为中心,因此,React灵敏!
有人能给我点建议吗?

body {
  margin: 0;
  padding: 0;
}

html {
  width: 100%;
  height: 100%;
}

h1 {
  font-family: "LiberationSansRegular";
  font-style: normal;
  font-weight: 600;
  font-size: 55px;
}

section {
  height: 100%;
  width: 100%;
  background-image: url(https://picsum.photos/seed/picsum/1200/800);
  background-repeat: no-repeat;
  background-size: cover;
  text-align: center;
}

/* parliament */

.img3 {
  height: 100%;
  width: 100%;
}
<main>
  <section>
    <h1>Hungarian Services at your fingertips</h1>
    <h2>
      Online lessons for kids and adults. Verbal and written training, best tailored to your needs. Translation services. All from a native speaker
    </h2>
  </section>
</main>
1tu0hz3e

1tu0hz3e1#

height: 100vh赋给section类。这样应该可以解决问题。

body {
  margin: 0;
  padding: 0;
}

html {
  width: 100%;
  height: 100%;
}

h1 {
  font-family: "LiberationSansRegular";
  font-style: normal;
  font-weight: 600;
  font-size: 55px;
}

section {
  height: 100vh;
  width: 100%;
  background-image: url(https://picsum.photos/seed/picsum/1200/800);
  background-repeat: no-repeat;
  background-size: cover;
  text-align: center;
}

/* parliament */

.img3 {
  height: 100%;
  width: 100%;
}
<main>
  <section>
    <h1>Hungarian Services at your fingertips</h1>
    <h2>
      Online lessons for kids and adults. Verbal and written training, best tailored to your needs. Translation services. All from a native speaker
    </h2>
  </section>
</main>
8tntrjer

8tntrjer2#

您似乎只需要设置background-position。(文本对齐不影响背景。)
Protip:为你的样式类使用直观的名称。img3不会告诉你的标记的读者任何关于它的功能。相反,使用类似.full-height.full-width的东西来应用这些样式(单独地),并使你的CSS可重用。

body {
  margin: 0;
  padding: 0;
}

html {
  width: 100%;
  height: 100%;
}

h1 {
  font-family: "LiberationSansRegular";
  font-style: normal;
  font-weight: 600;
  font-size: 55px;
}

section {
  height: 100%;
  width: 100%;
  background-image: url(https://picsum.photos/seed/picsum/1200/800);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  text-align: center;
}

/* parliament */

.img3 {
  height: 100%;
  width: 100%;
}
<main>
  <section>
    <h1>Hungarian Services at your fingertips</h1>
    <h2>
      Online lessons for kids and adults. Verbal and written training, best tailored to your needs. Translation services. All from a native speaker
    </h2>
  </section>
</main>

相关问题