Home > Articles

This chapter is from the book

9.8 Positioning

In this section, we are going to take a look at how positioning works in CSS, focusing on the site logo, and then we’ll finish off the header design. CSS positioning can be a little tricky, and honestly there are people who work with CSS all the time who regularly get confused trying to get positioning to work right. So if this section seems long and loaded with examples, just bear with us and work through it all—you’ll find that understanding CSS positioning is an essential skill.

When you style an element’s position, there are two basic possibilities:

  1. Have the browser draw the element in its natural position in the normal flow of content on the page.

  2. Remove the target from the flow of content and display it in a different place using directional styles—left, right, top, and bottom—and an additional dimension, the so-called z-index.

When an element is moved around out of its natural position with directional styles, it doesn’t affect other elements in the document—it either covers them up or is hidden behind them. It becomes like a ship cast adrift, torn free from its mooring on the page.

While it might be self-explanatory to move something left or right, or to change its top or bottom position, you might not be familiar with the idea of a z-index. The z-index property (usually a nonnegative number, 0 by default—negatives put elements behind everything) determines whether an element is displayed above or below other elements, as in farther “into” the screen or farther “out” toward the viewer. It’s an element’s 3D position.

You can think of this like looking down at a big stack of papers—the higher the z-index number is, the higher up the stack toward you the element is. A z-index of 0 would be the bottommost piece of paper. We’ll see a concrete example of the z-index in Section 9.9.

In order to change those directional styles, we first need to alter an element’s position property. The position style in CSS can be given five different values (though one of them isn’t really used). We’ll start with one of the most common one, static.

  • position: static (Figure 9.25)

    Figure 9.25

    Figure 9.25: How position: static affects elements.

    • This is the default positioning of elements in the flow of content.

    • An element that has no position style set, or has position: static, will ignore directional styles like left, right, top, and bottom.

  • position: absolute (Figure 9.26)

    Figure 9.26

    Figure 9.26: How position: absolute affects elements.

    • Positions the element at a specific place by taking it out of the document flow, either within a parent wrapper that has a position: value other than static, or (if there is no parent) a specific place in the browser window. It is still a part of the page content, which means when you scroll the page, it moves with the content.

    • Also lets you define a z-index property.

    • Because the element is removed from the document flow, the width or height is determined either by shrinking to the content inside or by setting dimensions in CSS. It behaves kind of like an element set to inline-block.

    • Causes any float that is set on the object to be ignored, so if you have both styles on an element you might as well delete the float.

  • position: relative (Figure 9.27)

    Figure 9.27

    Figure 9.27: How position: relative affects elements.

    • This is like static in that it respects the element’s starting position in the flow of content, but it also allows directional styles to be applied that nudge the element away from the boundary with other elements.

    • It allows absolutely positioned items to be contained within, as though the relatively positioned element were a separate canvas. In other words, if an absolutely positioned element is inside a relatively positioned element, a style of top: 0 would cause the absolutely positioned element to be drawn at the top of the relatively positioned element rather than at the top of the page.

    • Also allows you to change the z-index of the element.

  • position: fixed (Figure 9.28)

    Figure 9.28

    Figure 9.28: How position: fixed affects elements.

    • Positions the element at a specific place within the browser window totally separate from the page content. When you scroll the page, it won’t move.

    • Lets you set z-index.

    • Has the same need to have dimensions set as position: absolute; otherwise, it will be the size of the content inside.

    • Also causes floats to be ignored.

  • position: inherit

    • This is not very common, so we aren’t going to discuss it other than to say it makes the element inherit the position from its parent.

Let’s play around with some examples. First, let’s add in some styles for the header to better see the boundaries and to give it dimensions (Listing 9.23).

Listing 9.23: Added styles for the .header class.
css/main.css

/* HEADER STYLES */
.header {
  background-color: #aaa;
  height: 300px;
  width: 100%;
}

Let’s now absolutely position the .header-logo and set it to 50px from the bottom (Listing 9.24).

Listing 9.24: Adding an initial position: absolute to the logo.
css/main.css

.header-nav > li:first-child a:hover {
  color: #fff;
}
.header-logo {
  bottom: 50px;
  position: absolute;
}

Now save and refresh… where did the logo go (Figure 9.29)?

Figure 9.29

Figure 9.29: The parent container has no position style set.

The logo link ended up way at the bottom because the parent element that wraps the .header-logo doesn’t have any position style applied. Also, if you scroll the page up and down you’ll notice that the .header-logo still moves with the page. Let’s constrain the logo to stay within the header by adding a position property, as shown in Listing 9.25.

Listing 9.25: Setting a position other than static on the wrapper.
css/main.css

.header {
  background-color: #aaa;
  height: 300px;
  position: relative;
  width: 100%;
}

With the position rule in Listing 9.25, the .header-logo will now be 50px from the bottom of the gray header box, and any positions that we give to .header-logo will be determined based on the boundaries of the .header container (Figure 9.30). The way that the position is based off of the boundaries of the parent is what we meant when we said that setting a parent wrapper to position: relative made it like a separate canvas—everything inside that is absolutely positioned takes its place based on the dimensions of the parent.

Figure 9.30

Figure 9.30: The absolutely positioned .header-logo.

Note here that when an element is absolutely positioned, the directional styles don’t add or subtract distance—setting bottom: 50px doesn’t move it toward the bottom, but rather sets the position 50px from the bottom. So right: 50px puts the element 50px from the right edge.

Negative positions work as well, and as long as the overflow of the parent wrapper isn’t set to hidden, the absolutely positioned element will get placed outside the boundaries of the parent (Listing 9.26).

Listing 9.26: Trying out negative positioning on our object.
css/main.css

.header-logo {
  bottom: -50px;
  position: absolute;
  right: 50px;
}

After adding that style and refreshing your browser, the logo should be in a position similar to what is shown in Figure 9.31.

Figure 9.31

Figure 9.31: Positioning the logo on the right-hand side.

You might be asking, “Well, what happens if I set both a top and bottom, or a left and right?” The answer is that, for whatever reasons, the top and left properties will take priority and the bottom and right will be ignored.

Another thing to consider is when you set a position property, you are manipulating elements and messing around with the natural page flow, which means that it is possible to cause misalignments. So if you add left: 200px to the .header, the width of the element (which is 100%) isn’t recalculated. Instead, the entire .header box is pushed over by 200px, and your browser window will have horizontal scrollbars and look broken (Figure 9.32).

Figure 9.32

Figure 9.32: This sort of thing looks sloppy.

You have to be careful!

While we are still just playing around in the positioning sandbox, we should take a look at ways to deal with a situation that comes up anytime positioning in CSS is discussed: How do you center an absolutely positioned object horizontally and vertically in a way that allows the object to be any size… and allows the wrapper to be any size?

Let’s first look at an old method where the object that we are centering has a set height and width—centering this is easy. Give the logo a width and height, remove the old positioning, and change the background to better see the object (Listing 9.27).

Listing 9.27: Adding height and width dimensions to the logo.
css/main.css

.header-logo {
  background-color: #000;
  height: 110px;
  position: absolute;
  width: 110px;
}

Now let’s center it.

You might think that centering the element would be as simple as giving the .header-logo class a style of left: 50% and top: 50%—that should put it in the middle, both horizontally and vertically, right (Listing 9.28)?

Listing 9.28: Positioning the .header-logo in the center?
css/main.css

.header-logo {
  background-color: #000;
  height: 110px;
  left: 50%;
  position: absolute;
  top: 50%;
  width: 110px;
}

Well, no, the reason this didn’t work is that when the browser positions an object, it calculates the distance using the same-named edge—so when you apply top: 50%, it moves the top edge (not the center point) of .header-logo 50% away from the top of .header; similarly, applying left: 50% tells the browser to move the left edge 50% away from the left of .header. The result is that the object we are trying to position is off-center by half of its width and height (Figure 9.33).

Figure 9.33

Figure 9.33: The red box in the expected position if centered vertically and horizontally.

How do we solve this and get our object in the actual center? The older method mentioned above was to use a negative margin (Section 8.6.2) to move the object up and left. This only works if you know the size of the object, though, since trying to use something like a percentage would move the object based on the size of the parent (recall from Section 7.4 that percentage values are based on the size of the parent object). Since the height and width of the box are 110px, half of that is 55px (Listing 9.29).

Listing 9.29: Adding in the negative margins to position the black box in the right spot.
css/main.css

.header-logo {
  background-color: #000;
  height: 110px;
  left: 50%;
  margin: -55px 0 0 -55px;
  position: absolute;
  top: 50%;
  width: 110px;
}

That works just fine, but you’d always be limiting yourself to centering only objects with fixed dimensions (Figure 9.34).

Figure 9.34

Figure 9.34: Negative margins worked!

If you wanted to make a slightly bigger (or smaller) centered object, you’d have to recalculate sizes and margins, and then make changes to your CSS. That’s too much work, and it wouldn’t work at all with dynamically sized elements. Thankfully there is a better, relatively new CSS style called transform that can help. The transform property allows developers to do all sorts of amazing things like move objects around, rotate them, and simulate three-dimensional movement.

The upside for centering objects is that this new style calculates all these movements based on the object itself. So if we move it 50% to the left using transform, the browser looks at the object’s width, and then moves it to the left 50% of its own width, not the width of the parent.

The actual style declaration looks like this: transform: translate(x, y)— where x is replaced by the distance along the x-axis (left is negative, right is positive), and the same for the y-axis (up is negative, down is positive). So, to move our object left and up half its width and height, we’d add the transform style like you see in Listing 9.30 (make sure to remove the margin styling that we added in Listing 9.29).

Listing 9.30: Moving an object using transform.
css/main.css

.header-logo {
  background-color: #000;
  height: 110px;
  left: 50%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 110px;
}

Now when you save your work and refresh the browser you’ll have a black box in the center of the gray header. It doesn’t matter what dimensions you give for either the .header-logo or .header—you’ll always have a vertically and horizontally centered object. To try it out, delete the height and width that we gave the .header-logo.

When you save and refresh your browser, the now-smaller box will still be centered vertically and horizontally (Figure 9.35).

Figure 9.35

Figure 9.35: No matter what size the object is, it stays right in the center.

9.8.1 A Real Logo

All right, enough positioning playtime. Let’s get back to making this site look good by putting an actual logo in that .header-logo. In your project directory, add a new folder called images (Figure 9.36):

Figure 9.36

Figure 9.36: New images folder in your project directory.

$ mkdir images

Then use this curl command to grab the logo image off the Learn Enough servers:

$ curl -o images/logo.png -L https://cdn.learnenough.com/le-css/logo.png

Now let’s put the image into the header.html (Listing 9.31). The result appears in Figure 9.37.

Figure 9.37

Figure 9.37: The initial (sub-optimal) logo placed on the page.

Listing 9.31: Replacing the word logo with a logo image.
_includes/header.html

<header class="header">
  <nav>
    <ul class="header-nav">
      <li><a href="/">Home</a></li>
      <li><a href="#">Nav 1</a></li>
      <li><a href="#">Nav 2</a></li>
      <li><a href="#">Nav 3</a></li>
    </ul>
  </nav>
  <a href="/" class="header-logo">
    <img src="/images/logo.png" alt="Learn Enough">
  </a>
</header>

Now we are going to make a whole lot of changes to whip this part of the site into shape. As in Section 9.6.2, we aren’t going to go through and give a reason why each value is the exact number we chose. Styling a section of a site is a non-linear process at times, and you’ll likely need to experiment a lot if you are doing this on your own starting from a blank slate.

First, we are going to make the header background color black and any text in the header white as follows:

.header {
  background-color: #000;
  color: #fff;
}

That’s also going to require that we change the color of the links, as well as the rollover color for the first-child link in the navigation:

.header-nav > li:first-child a:hover {
  color: #fff;
}

We’ll also need to change the background color of our little divider lines so that it is partially transparent white instead of partially transparent black:

border-left: 1px solid rgba(255, 255, 255, 0.3);

Then we are going to move the .header-logo into the top left, and shrink the image a bit:

.header-logo {
  background-color: #000;
  box-sizing: border-box;
  display: block;
  height: 10vh;
  padding-top: 10px;
  position: relative;
  text-align: center;
  width: 10vh;
}
.header-logo img {
  width: 4.3vh;
}

We chose 10vh for the size of the link, and for the image we set the width to be 4.3% of the height of the container (4.3vh). We got those values after playing around with different numbers and settling on this size for a balance of readability while not taking up too much space.

You’ll notice that most of the sizing styles are on the link that wraps the image and not on the image itself. The reason we did that was so that if there is a problem downloading the image, or a delay, there is still a nice, big clickable link in the header.

Putting everything together gives us Listing 9.32, which includes all the styling for the site header so far.

Listing 9.32: Changing up the styling for the header and logo.
css/main.css

/* HEADER STYLES */
.header {
  background-color: #000;
  color: #fff;
}
.header-logo {
  background-color: #000;
  box-sizing: border-box;
  display: block;
  height: 10vh;
  padding-top: 10px;
  position: relative;
  text-align: center;
  width: 10vh;
}
.header-logo:hover,
.header-logo:active {
  background-color: #ed6e2f;
}
.header-logo img {
  width: 4.3vh;
}
.header-nav {
  float: right;
  padding: 5.5vh 60px 0 0;
}
.header-nav > li {
  display: inline-block;
  margin-left: 1em;
}
.header-nav > li ~ li {
  border-left: 1px solid rgba(255, 255, 255, 0.3);
  padding-left: 1em;
}
.header-nav a {
  color: #fff;
  font-size: 0.8rem;
  font-weight: bold;
  text-decoration: none;
  text-transform: uppercase;
}
.header-nav a:hover,
.header-nav a:active {
  color: #ed6e2f;
}
.header-nav > li:first-child a {
  color: #ed6e2f;
}
.header-nav > li:first-child a:hover {
  color: #fff;
}

Save and refresh, and your header should look like Figure 9.38. That logo’s lookin’ sharp!

Figure 9.38

Figure 9.38: The header, now styled.

9.8.2 Exercise

  1. Try moving the ul that contains the social links to the bottom-left corner of the .full-hero using the positioning rules you’ve learned. What changes are you going to need to make to .full-hero to allow the social links to remain inside?

  2. To see why we gave dimensional styling and an alt tag to our image, try removing the image source link to simulate the browser not finding the file.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020