html - 如何正确对齐元素?

标签 html css

所以我在左侧有一个菜单项“header”(深色)。在右侧,我将有我的英雄“主页”页面和下面的“部分”。我唯一想要的滚动条是向上/向下滚动,没有左右滚动,我想将主要/部分页面居中。

所以第一个“标题”元素将是:

width: 80px;

现在,我希望其他元素(例如“main”)坚持该菜单项。目前我的问题是我必须不断更改“英雄”页面的数字,以便它在中心正确对齐,但这很痛苦,我似乎无法正确设置数字,我总是得到任何一个页面都像菜单后面的 2px或相反。

那么有什么方法可以重写代码,即使我更改菜单宽度,“主要”部分也会自动粘在“菜单”栏的一侧?

https://codepen.io/MariusZMM/pen/xmPraj

<div id="header"></div>

  <div id="main">
    <div class="box"></div>

    <div id="sections">
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla sunt repudiandae unde doloremque eos sed
        dolorem sit quae totam impedit. Exercitationem ad alias quae ipsam, maxime molestias quibusdam fugit
        doloribus.
      </p>
    </div>
  </div>

CSS

body {
  margin: 0;
  padding: 0;
}

#header {
  background: #222629;
  height: 100%;
  left: 0;
  position: fixed;
  text-align: center;
  top: 0;
  z-index: 1;
  overflow-y: auto;

  /* Menu size*/
  width: 80px;
}

#main {
  position: absolute;
  height: 100%;
  background-color: #856030;

  /* Hero page size*/
  margin-left: 6.25%;
  width: 97.5%;
}

.box {
  width: 100%;
  position: relative;
  height: 100%;
}

#sections {
  position: absolute;
  background-color: #347424;
}

最佳答案

我想我已经弄清楚了,在 CodePen 上更新 https://codepen.io/MariusZMM/pen/Newvqb

所以我所做的是,“主要”部分使用“左”,并将其设置为与菜单相同的像素数。然后还添加了“left: 0;”对于“标题”

这是处理此问题的正确方法还是有更好的方法?

body {
  margin: 0;
  padding: 0;
}

#header {
  background: #222629;
  height: 100%;
  left: 0;
  position: fixed;
  text-align: center;
  top: 0;
  z-index: 1;
  overflow-y: auto;

  /* Menu size*/
  width: 80px;
}

#main {
  position: absolute;
  height: 100%;
  right: 0;

  background-color: #2c2419;

  /* Hero page size*/
  left: 80px;
  width: auto;
}

.box {
  width: 100%;
  position: relative;
  height: 100%;
}

#sections {
  position: absolute;
  background-color: #347424;
  width: 100%;
}

关于html - 如何正确对齐元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53984581/

相关文章:

javascript - 在 MouseOver 和 onMouseOut 上隐藏和显示图像 - 图像立即重新出现

javascript - onload 与 addEventListener 的 iframe 行为 ('load' )

html - 选定的页面链接问题

html - 使用 float 的特定布局

html - 带有背景颜色的 Logo 图像浏览器问题

javascript - HTML <select> 元素发送默认选择,即使未选择

jquery - 收到错误消息 "Uncaught TypeError: Object .gearImg has no method ' css' "

javascript - JQuery 图像 slider 中的自动增量图像

html - ffox/chrome 中的 Colgroup

css - 如何在单页响应中在 bootstrap 3 中设置 2 个导航栏