How do I control how a html element is displayed in css?



  • HTML elements are either block level elements or inline elements by default, without any CSS properties.

    Block level HTML element.

    • Always starts on a new line.
    • Always takes up the full width available.
    • A block level element has a top and a bottom margin

    Inline level HTML element.

    • Does not start on a new line.
    • Only takes up as much width as necessary.

    There is also a third value to the CSS display property, inline-block discussed further down the article.

    This is an example of CSS controlling the display of an HTML element. The paragraph HTML element is by default an inline element. This CSS code puts a border around the element to show how the space around it is used.

    Display a HTML element as inline using CSS.

        <style>
            p {
                display: inline;
                border: solid 2px rgb(9, 6, 175);
                background-color: #6ab86a;
                color: #fff;
                font-size: 25px;
            }
        </style>
    

    The HTML snippet is.

    ...
    <p>Lorem ipsum dolor sit amet.</p>
    ...
    

    The result is
    5146f231-5edb-4c6a-9725-995b69f176ed-image.png

    Lets's change the CSS code to display it as a block level element.

        <style>
            p {
                display: block;
                border: solid 2px rgb(9, 6, 175);
                background-color: #6ab86a;
                color: #fff;
                font-size: 25px;
            }
        </style>
    

    The result is:
    7b409295-cd38-4bb3-bec9-809b721fecc4-image.png

    You can see that the entire width is taken up and although not visible in the image, there is a top and bottom margin.

    The CSS display property can also have a value of inline-block

    The difference between inline and inline-block, inline-block allows a set width and height on the element and the top and bottom margins and padding is respected.

    The difference between block and inline-block inline-block does not add a line-break after the element, so the element can sit next to other elements.

     <style>
            p {
                display: inline-block;
                border: solid 2px rgb(9, 6, 175);
                background-color: #6ab86a;
                color: #fff;
                font-size: 25px;
            }
        </style>
    

    The HTML changed to the following:

    ...
    <p>Lorem ipsum dolor sit amet.</p>
    <p>Lorem ipsum dolor sit amet.</p>
    ...
    

    The results is:
    e6d92911-6541-44d5-b29d-4e557a8164de-image.png


Log in to reply
 

© Lightnetics 2024