Friday, July 29, 2016

ASP.NET Core : Create A Responsive Layout With Bootstrap

In our previous blog we created a simple _Layout.cshtml file that does not have any markup just to make things simple. In this blog we will use Bootstrap to make the layout look more professional and responsive, so that it can be viewed in any screen size. The previous layout looks like screenshot below.

The Bootstrap version will look like the screenshot below.

Step-By-Step Instructions:

1. Open the NorthwindCafe.Web project

2. Now we are ready to add the header navigation to the _Layout.cshtml file, which is the layout specified as the default layout in the _ViewStart.cshtml file.

The code above defines the viewpoint as the device-width, a viewport is the width of the screen used to determine how bootstrap will display the elements on the screen. The device-width viewport means that the elements will be render to the screen's device width. The rest of the code just links to Bootstrap css and JavaScript files, and jQuery. You can find these files in the wwwroot → lib folder

4. Once we have the head section defined we can define the header section of the layout.

The code above looks complicated, but it's not that complicated. First we use the bootstrap class "navbar navbar-default navbar-fixed-top" to tell the browser that we want the navbar that is fixes on the top of the screen even when the user scrolls.
All we have to do is define the class and bootstrap does the rest for us. The navbar class defines the top navigation of the layout like the screenshot below

5. The following section defines the menu when the screen gets really small and the elements have to be stacked because it does not have the width to display everything horizontally.

Like everything else in bootstrap we just have to call class "navbar-collapse collapse" and nest the div with the <ul> element with class "nav navbar-nav" and bootstrap picks it up applies the stylesheets and functionalities automatically. That's the great thing about bootstrap. It makes things easy, but the bad thing is a lot of the sites nowadays have the same bootstrapy look and feel to them. But it's great if you want to throw something together quickly and make it look decent.

8. To style the jumbotron we have to create our own stylesheet so that it does not interfere with the default bootstrap styles. So create a new css file in the wwwroot → css folder and give it the name Styles.css.

The code above defines the margin for the navbar and the jumbotron, it also set the text color and background color for the jumbotron.

But what about the issue we had with the dropdown menu being cutoff? To solve this issue we want to add a css property of overflow: visible to the navar class. That just tells css to to make the the dropdown menu visible when it goes outside of it's container. Now you will see that the dropdown menu is displayed even in mobile mode.