首页 > 解决方案 > 如何使用 css 将三个元素并排放置并居中

问题描述

我对 css 和 web 开发还很陌生,我想使用 react 创建一个新的 pwa,我需要一个标题,其中一个我在左边,一个居中的文本在中间,另一个我在右边标题。到目前为止一切都很好,我无法成功地将它们放在一起,但我不能以响应的方式做到这一点。这意味着,当我使用 chrome 检查并将横向从垂直切换到水平时,应该位于中心的文本会向左移动一点。我知道这是我的代码,但我不知道如何解决这个问题以及如何让这个思考响应。

我想问题出在.headerApp p,我在这里留下了边距。有什么方法可以在不需要任何边距的情况下将其显示在中心?

这是我的html代码:

.headerApp {
  background-color: #57628d;
  height: 4rem;
  border-style: solid;
}

.headerApp .backButton {
  width: 36px;
  height: 36px;
  float: left;
  margin-top: 0.9rem;
  margin-bottom: 2%;
  margin-left: 1rem;
}

.headerApp p {
  color: white;
  float: left;
  width: 50%;
  position: relative;
  font-family: "Ubuntu";
  font-weight: normal;
  font-size: 32px;
  margin-top: 0.8rem;
  margin-left: 10%;
}

.headerApp .toProfile {
  width: 44px;
  height: 44px;
  float: right;
  margin-right: 1rem;
  margin-top: 0.5rem;
}
<header className="headerApp">
  <img className="backButton" src={require( "../assets/back.png")} alt="back button" />
  <p>Fahrt nach</p>
  <img className="toProfile" src={require( "../assets/Profil.png")} alt="go to own profile" />
</header>

标签: javascripthtmlcssreactjsresponsive-design

解决方案


您可以使用网格来实现这一点

.headerApp{
  display:grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-auto-flow: column;
}
<header class="headerApp">
      <img
        class="backButton"
        src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=650&w=940"
        alt="back button"
        height="40px"
        width="40px"
        
      />
      <p>Fahrt nach</p>
      <img
        class="toProfile"
        src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=650&w=940"
        alt="go to own profile"
         height="40px"
        width="40px"
      />
  </header>`

使用Flexbox你可以这样做

.headerApp{
  display: flex;
  justify-content: space-between;
}
<header class="headerApp">
          <img
            class="backButton"
            src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=650&w=940"
            alt="back button"
            height="40px"
            width="40px"
            
          />
          <p>Fahrt nach</p>
          <img
            class="toProfile"
            src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=650&w=940"
            alt="go to own profile"
             height="40px"
            width="40px"
          />
      </header>`


推荐阅读