首页 > 解决方案 > 我怎样才能居中

代替

问题描述

如何<p>在 div 中放置一个?当我使用text-align:center;它时,它从全宽居中,但我希望它位于侧边栏末端的中心。我也尝试过float: center;,但也没有用。 https://jsfiddle.net/umklapper/4be1pus5/2/ 我想要的是:

           |
sidebar    |<------------------------------center----------------------------------------------->
           |

.menu {
  height: 100%;
  width: 160px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  padding-top: 20px;
}

.item {
  margin: 5px 0 5px 0;
  font-size: 25px;
  color: white;
  text-decoration: none;
  text-align: center;
  padding: 20px;
  font-family: Comic Sans MS;
}

.video {
  margin: 0 auto;
  width: 400px;
  /* Same width as the sidebar + left position in px */
  font-size: 28px;
  /* Increased text to enable scrolling */
  padding: 0px 10px;
  text-align: center;
}
<div class="menu">
  <a href="" class="item">About Me</a>
  <a href="" class="item">Trips</a>
  <a href="" class="item">Books</a>
  <a href="" class="item">Foods</a>
</div>
<div class="video">
  <p>Hey! Welcome to my website!</p>
  <iframe width="560" height="315" src="https://www.youtube.com/embed/-ObdvMkCKws" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
        </iframe>
</div>

标签: htmlcss

解决方案


问题是你的侧边栏有固定的位置,所以它不会影响其他内容的定位。尝试查看flex 布局。您应该将整个内容、侧边栏和内容包装在flex父级中,然后将内容居中在.video.

html {
  height: 100%;
}
body {
  padding: 0;
  margin: 0;
  height: 100%;
}
.wrapper {
  display: flex;
  align-items: stretch;
  height: 100%;
}
.menu {
  width: 250px;
  z-index: 1;
  background-color: #111;
  padding-top: 20px;
}

.item {
  font-size: 25px;
  color: white;
  text-decoration: none;
  text-align: center;
  padding: 20px;
  font-family: Comic Sans MS;
  display: block;
}

.video {
  padding: 0px 10px;
  font-size: 28px;
  text-align: center;
  flex: 1;
}
<div class="wrapper">

  <div class="menu">
    <a href="" class="item">About Me</a>
    <a href="" class="item">Trips</a>
    <a href="" class="item">Books</a>
    <a href="" class="item">Foods</a>
  </div>
  <div class="video">
    <p>Hey! Welcome to my website!</p>
    <iframe src="https://www.youtube.com/embed/-ObdvMkCKws" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
        </iframe>
  </div>
</div>


推荐阅读