HTML/CSS: Nav bars on the left side of page

2020-06-28 01:26发布

I find it awkward to create layouts like this that have good semantics.

The left side is a column about 150 pixels wide which contains navigation elements.

I would like to put the HTML for this section of the site at the beginning of the HTML code, and then have an easy way to force the rest of the page not to encroach on that territory on the left (the 150 pixel column).

I have thought about some options.

  1. Place rest of site content inside a div which explicitly has a left-margin of 150px.
  2. Set the nav element to width 150px and float left. The rest of the page naturally wraps.

Are there other options that are more suitable for this task?

Here are the cons.

  1. Changing the nav element to 200px now requires me to edit the left-margin of the other div to 200px. Sure, this isn't too bad for a one-time layout change, but what if I had the nav element's width dynamically change from script? I would need the script to also change the margin of the div.
  2. If the nav element is set to position:fixed (and made to occupy the entire left column of the page) the rest of the page's wrapping does not accomodate its now stationary behavior and it looks terrible when the page is scrolled. To fix this I need to make the nav element infinite height. I am not sure how to do this the right way. height:9999999px;? That makes my page 10 million pixels high and the scrollbar is now useless.

标签: html css layout
3条回答
smile是对你的礼貌
2楼-- · 2020-06-28 01:45

Create sidebar:

<!-- html -->
<nav role="main">
  <a href="link.com">link</a>
</nav>

//css
nav{    
  width: 150px;
  float: left;
  display: inline;
  margin: 0;
  padding: 0;
  margin-right: 10px;
}

Then create a container for your main content

<!-- html -->
<section id="main">
  main content in here
</section>

//css
section#main{
  width: 500;
  float: left;
  margin: 0;
  padding: 0;
  display: inline;     
}

As long as you place nav before section in your source code, anything that is in the section will stay away from the left hand column and will not wrap under it.

Just need to make sure you reset all your css, especially paddings, margins and borders unless you know what you're doing

good luck

查看更多
老娘就宠你
3楼-- · 2020-06-28 01:47

I have always used option 1, though if there are other ideas out there, I'd love to hear about them.

查看更多
欢心
4楼-- · 2020-06-28 01:53

Few suggestions for your 'cons':

  1. If you are tired of changing two properties with the same value all the time, consider using CSS generation tools like LCSS, SASS.
  2. If I remember correctly, instead of setting height: 999999px for the left sidebar, some tricks like this one do exists: http://www.ejeliot.com/blog/61
查看更多
登录 后发表回答