I was asked by a visitor how he could create a box, give it a background colour ("color" if you use a different variant of English), and insert text in it, the way some printed magazines and books sometimes place additional information in a separate box or panel on a page.
This article assumes that you know a bit of HTML and CSS. Otherwise you will be at a loss as to where to put the code I supply below or how to adapt it for your purpose.
The box itself can be any block tag in HTML. Many, if not most, webmasters use a <div>
for this purpose.
Let's say that you have the following HTML snippet that you want to make into a box.
The CSS to give the DIV block a background colour is, predictably:
The background-color
rule above specifies the HTML colour value of #cfc
. You can of course
use any other colour you like. Most web
editors and plain text editors
(other than the rudimentary Notepad that comes with Windows) have a colour picker, allowing you to visually select a colour
to get the appropriate numerical value. Alternatively, if you prefer to do things the hard way, you can also consult the
list of colours and their values on Wikipedia.
Unfortunately, although the above code is correct, if you use it as it stands, you will find that the background colour will hug the text you place very closely, causing the entire thing to seem barely like a box. To make things more box-like, you will probably want to add some space to the area around your text, and perhaps even give it a border.
The padding
rule adds 10 pixels to the space between your text and the margins of the box,
and the border
rule creates a 1-pixel thick solid green border. You can of course change
the values given here (ie, the number of pixels and the colour) to suit your page's design.
If you're posting to a blog that allows you to insert HTML, but does not make it easy for you to change the style sheet, you can even put those rules into your DIV tag.
The above code produces the following box.
The CSS given above should work in all current browsers. It will probably even work in most older browsers too, including Internet Explorer 6 (which is most likely extinct today).
Copyright © 2017-2024 Christopher Heng. All rights reserved.
Get more free tips and articles like this,
on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/.
Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.
This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.
It will appear on your page as:
How to Create a Coloured ("Colored") Box in HTML/CSS