css 为什么这个图像有时居中,有时不居中?

63lcw9qa  于 2023-06-25  发布在  其他
关注(0)|答案(3)|浏览(140)

我没有修改代码里的任何东西。
有时当我加载页面时,图像在水平和垂直方向上居中,但有时它只在水平方向上居中。

图片居中:

图像未居中:

.wavySectionContainer {
  height: 100%;
  width: 100%;
  background-color: var(--primary);
  position: relative;
}

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

<div class="wavySectionContainer">
    <img class="sun"  src="public/sun.png" alt="Wave">
    <p class="aboutMe">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Eligendi officia, mollitia
        cupiditate quae quos voluptatem dolorum? 
        <br><br>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit.
    </p>
</div>
ego6inou

ego6inou1#

下面的代码使用CSS Grid将段落放置在图像上方,然后使用align-itemsjustify-items将它们居中。

html,
body {
  height: 100%;
}

.wavySectionContainer {
  height: 100%;
  width: 100%;
  display: grid;
  grid-template-areas: "content";
  align-items: center;
  justify-items: center;
}

.aboutMe,
.sun {
  grid-area: content;
}
<div class="wavySectionContainer">
  <img class="sun" src="https://placekitten.com/200/300" alt="Wave">
  <p class="aboutMe">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Eligendi officia, mollitia cupiditate quae quos voluptatem dolorum?
    <br><br> Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  </p>
</div>

(我没有你的图像,所以我使用了PlaceKitten。

35g0bw71

35g0bw712#

试试这个,它会很好地工作。

.wavySectionContainer {
  height: 100vh;
  width: 100%;
  background-color: blue;
  position: relative;
}

.aboutMe,
.sun {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="wavySectionContainer">
        <img class="sun"  src="https://i.ibb.co/C23WVJ2/pngegg.png" alt="Wave">
        <p class="aboutMe">Lorem ipsum dolor sit amet consectetur adipisicing elit. Eligendi officia, mollitia cupiditate quae quos voluptatem dolorum? <br><br>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
      </div>
ryhaxcpt

ryhaxcpt3#

使用height 100vh(viewport height)and width 100vw(viewport width)或者使用固定的高度和宽度的px(pixels)值,那么你就会得到想要的输出。

.wavySectionContainer {
  height: 100vh;
  width: 100vw;
  background-color: blue;
  position: relative;
}

.aboutMe,
.sun {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  
}
<div class="wavySectionContainer">
        <img class="sun"  src="https://images.vexels.com/media/users/3/147002/isolated/lists/ebeb92f867932e57e096ebc64a3f884f-abstract-sunshine-rays-icon.png" alt="Wave">
        <p class="aboutMe">Lorem ipsum dolor sit amet consectetur adipisicing elit. Eligendi officia, mollitia cupiditate quae quos voluptatem dolorum? <br><br>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
      </div>

相关问题