且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有旋转文本的垂直导航

更新时间:2023-11-02 11:47:58

Rotating each a element or li element will make us encounter some problem spacing, positioning the elements exactly as we want. We should build the navigation menu so that it spreads horizontally, looks OK first then we just to need rotate the whole container of the navigation menu. Here is the updated code:

.main-nav {
  width:100vh;    
  height:45px;
  position:fixed;
  background:#4c4c4c;
  -webkit-transform-origin: left top;
  -webkit-transform:rotate(-90deg) translateX(-100%);
}
ul.nav li {    
  margin-right:20px;
  float:right;
  height:100%;
  line-height:45px;
}

The menu is supposed to have fixed height of 45px (after rotated, it will be the width). We use line-height:45px to center the a element vertically (after rotated, it will be horizontally). At first the .main-nav will lie horizontally like this:

we need to rotate it -90deg (which is counter-clockwise) around the point left - top specified by transform-origin: left top. After rotated, all the .main-nav will be out of view like this:

So we need to translate it down a distance of 100% of width, however note that we don't use translateY which seems to mean translate it vertically, because after rotated, the X axis becomes vertical (not horizontal as before), so we have to use translateX(-100%) (the positive direction is upwards, it's rightwards before rotated). Then we have:

It's just a simple use case related to transform in CSS3. For the vh unit, it's the unit relative to the viewport's height. 100vh means 100% of viewport's height. We have to use 100vh for the width because after rotated, width becomes height. It should fill the full height of the viewport. However you can set some min-width for the width by px to limit the width's minimum value. It's because when you resize the window, the viewport's height may become small and hence the width will be shrunk accordingly. Also note that instead of using float:left for the li elements, we have to use float:right so that the Home menu appears first from top to bottom, otherwise (using float:left), the Home menu will appear at the end (at bottom). There is a little advanced usage of the transform here (to newbie) it we use more than 1 transform for a transform property, all the transforms are separated by space and the order of transforms is important. Such as rotate(-90deg) translateX(-100%) means rotating -90deg first, then translating along the X axis -100%, while translateX(-100%) rotate(-90deg) is reverse to that, it's a totally different thing and of course won't work (makes an unexpected result).

Jsbin Demo.