Methods and techniques to display multiple elements on one line

1. Use display: inline;

  • We can use display:inline to convert an element to an inline element, but its length and width are the length and width of its content. Setting the attribute does not work.
  <style>
        /* 方法一*/
        
        .box1,
        .box2 {
            display: inline;
            width: 200px;
            height: 2000px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="box1">盒子一</div>
        <div class="box2">盒子二</div>
    </div>
</body>

Insert picture description here

2. Use display: inlien-block
Use display: inline-block; you can put elements on one line for display, but they will be affected by the space/line feed key and have a default spacing.
Solution:

  • You can add font-size to the parent element with display:inline-block, but the content in the default child element will disappear. At this time, add font-size to the child element to overwrite the font-size of the parent element.
  • 2. Remove the impact of spaces and line breaks, but this may affect the readability of the code, it is not standardized, and it is not recommended to use
    <style>
        /* 方法二 display: inline-block;*/
        
        * {
            padding: 0px;
            margin: 0px;
        }
        
        .box {
            font-size: 0px;
        }
        
        .box1,
        .box2 {
            display: inline-block;
            width: 200px;
            height: 200px;
            font-size: 24px;
            text-align: center;
            background-color: pink;
        }
        
        .box2 {
            background-color: red;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="box1">盒子一</div>
        <div class="box2">盒子二</div>
    </div>
</body>

Insert picture description here

3. Use float float: left/right, but remember that the easiest way to clear float is to add overflow: hidden to the parent element.
Note:

  • There is no gap in the floating float
  • If you use floating display: inline-block, it will have no effect
    <style>
        /* 方法二 浮动float*/
        
        * {
            padding: 0px;
            margin: 0px;
        }
        
        .box {
            overflow: hidden;
            /* 清除浮动 */
        }
        
        .box1,
        .box2 {
            float: left;
            width: 200px;
            height: 200px;
            text-align: center;
            background-color: pink;
        }
        
        .box2 {
            background-color: red;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="box1">盒子一</div>
        <div class="box2">盒子二</div>
    </div>
</body>

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46978034/article/details/110482479