A Simple 2-Column Layout in Razor

Monday, August 22, 2011

2 column layouts are rather popular on the web, and there are 1,001 ways to make them work. The approach you choose really depends on the type of content you have, and how you want images and backgrounds to work. What I'll show is the Razor _Layout and CSS to achieve the following look:


The Razor _Layout file can rely on partial views to handle each of the primary sections: top, navigation, sidebar, and footer. RenderBody will produce the primary content area.

<!DOCTYPE html>
    <link href="@Url.Content("~/Content/Site.css")" 
          rel="stylesheet" type="text/css" />

    <div id="body">

A quick note on Html.Partial. If any sections, like the sidebar and navigation sections, require some logic or model information to build their piece of the UI, then use Html.Action instead of Html.Partial. Html.Action allows you to setup a little sub-request inside the current request and allow a controller action to build a model and select a view.

The CSS coming up assumes each partial view will render inside an element with an id matching it's purpose (so the _top view renders a div with an id of top).

<div id="top">
    This is the top content

Then finally, add some styles to the CSS file: 

#top {
    height: 20px;
    text-align: center;
    background-color: black;
    color: white;   

#navigation {
    height: 25px;
    margin: 5px;
    padding: 5px;

#sidebar {
    margin: 5px;
    padding: 5px;
    position: absolute;
    top: 50px;
    left: 314px;

#body {
    width: 300px;
    padding: 5px;
    margin: 5px;
    background-color: #999999;
    border-radius: 5px;
    border: 2px black solid;

#footer {
    padding: 5px;
    text-align: center;
    background-color: black;
    color: white;

The trick is to use absolute positioning on the sidebar content, which is possible because we know the exact amount of space taken by the 2 sections at the top of the page, and we know the exact width of the content area (it is set explicitly in the CSS). You'll probably want to give the body more space than the 300px given in the sample above (which was constrained so the screenshot would fit on this page).

Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!