search
HomeWeb Front-endHTML Tutorial【干货】:如何让元素水平排列?_html/css_WEB-ITnose

  块级元素默认是垂直排列的,而行内元素是水平排列的,而在布局时基本上都是用块级元素,如div等常用块级标签,那么如何让块级元素也进行水平排列呢?我有100种方式(准确说是100-94种)让元素水平排列,你知道几种呢?

第一种:display:inline-block

  首先得先了解块级元素(block elements)和行内元素(inline elements)以及行内块状元素(inline-block elements)

    块级元素:块级元素包含width height,padding,border与margin,他们的排列方式是从上到下排列,常见的块级元素有div,p,form,ul等等,更多块级元素的可以去MDN上查阅https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements

    行内元素:高度和宽度由内容决定,自身没法设定固定的大小,不存在垂直方向的margin和padding,排列方式是水平排列,行内元素在html所有元素占大多数,比如a,span,label,button,img,input......更多行内元素还是MDN查阅https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements

    这里可能有人会产生疑问,“button和img以及input等标签可以设置宽度和高度也可以设置margin与padding,为什么它确实行内元素呢?”其实html元素主要有两种划分方式,分别是“块级元素与行内元素”,“替换元素与不可替换元素”。上面介绍了第一种划分方式,下面介绍一下第二种划分方式:

    替换元素:通俗的理解就是具有width和height属性的元素。替换元素类似于display:block元素,可以设置高宽与内外边距,主要包括img , input , textarea , select , object,audio和canvas在某些特定情形下为替换元素。更官方的定义https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element

    不可替换元素:除了替换元素剩下的都是不可替换元素(O(∩_∩)O)

扯了一大堆,我们知道display:inline-block可以让元素横向排列,但是这种布局可能会存在一点点小问题,举栗子:

<style>        div{            display:inline-block; width:200px; height:200px; } .div1{ background:green; } .div2{ background:red; }</style><div class = "div1">左边</div><div class = "div2">右边</div>

这是我们发现两个div之间存在一个空隙,这是为什么呢?

  浏览器会将换行符,缩进符,以及空格当做一个空格来处理,即使暗恋两次空格,或者一个换行加一个空格,等等都会解析成一个空格使用。这个空格的大小则是font-size/2大小。去除这个空隙有很多办法。

  1.设置div2的margin-left:-font-size/2

  2.设置两个div的父标签的font-size:0

  3.设置负的word-spacing

等等还有好多方式,此处只是抛砖引玉,具体细节可以看一下张鑫旭的这篇博客,研究的很细致。http://www.zhangxinxu.com/wordpress/2012/04/inline-block-space-remove-%E5%8E%BB%E9%99%A4%E9%97%B4%E8%B7%9D/

第二种:float:left/right

  float属性可以让元素脱离常规文档流,沿着容器的左侧或者右侧进行水平排列。

  这种方式可以说是用的最多的,但是有个问题,在自适应布局中一般不会固定元素的高宽,会根据内容大小来自动调整,这是如果子元素都是浮动元素的话就会存在高度塌陷。

举栗子

<style>        span{            float:left; width:200px; height:200px; } .box1{ background:green; } .box2{ background:red; }</style><div> <span class = "box1">左边</span> <span class = "box2">右边</span></div>

  这里将上一个栗子中的子元素div故意改成了span,其实想表达float可以将元素隐式的转换成block元素(position:absolute/fixed亦可),所以自然就可以设置宽度和高度。

那么盒子水平排列之后存在什么问题呢?没错!父容器高度塌陷。这时父容器div的高度为0,因为浮动元素会脱离常规文档流,它的父容器计算高度时会忽略它。这是我们不想看到的,因为这个高度塌陷的DIV后面如果还有其它常规流标签的话,那么页面就会出现错乱等不想看到的结果。

  解决办法自然就是清除浮动,主要通过两种方式清除浮动:

    1.clear:left/right/both,专门用来清除浮动的CSS。

    2.BFC,因为BFC有一条规则“计算BFC的高度时,浮动元素也参与计算”。

  说一下用clear清除浮动的几种方法:

    1.最后一个子元素后面加一个空标签,然后设置其样式clear:both。

    2.在最后一个浮动子元素中,利用伪元素::after,添加clear样式清除浮动

  通过BFC解决高度塌陷:

    为父元素创建BFC(摘自MDN),只要满足以下任何一种都会为元素创立BFC。

A block formatting context is created by one of the following:

  • the root element or something that contains it
  • floats (elements where float is not none)
  • absolutely positioned elements (elements where position is absolute or fixed)
  • inline-blocks (elements with display: inline-block)
  • table cells (elements with display: table-cell, which is the default for HTML table cells)
  • table captions (elements with display: table-caption, which is the default for HTML table captions)
  • elements where overflow has a value other than visible
  • flex boxes (elements with display: flex or inline-flex)
  • 我英语不好,上面的英文也能看懂,所以它就不需要翻译了吧,建议动手试一下。

    第三种:table布局

      这种布局方式其实不常用,因为它存在种种问题。

        ·渲染速度较慢

        ·增加html代码量,不易维护

        ·标签的名字不符合html语义化,table本来就是做表格用的,拿来布局甚是不妥

        ·标签结构较死,后期修改成本较高

    等等,此处不作过多阐述。总之,尽量用table布局

    第四种:绝对定位

      这种方式日常开发中用的也较多,前面提到float可以让元素脱离常规文档流,这里position:absolute/fixed也具有同样的效果,处理办法在float布局中已经提到了,这里搬来即可。

      这里要说一下position:absolute绝对定位,以它的第一个父级并且是position:absolute/relative/fixed定位的元素为基点进行定位,如果找不到则以根元素为基准进行定位。一般都是采用父元素position:ralative,子元素position:absolute结合使用。

    第五种:css3的弹性布局

      html5的新特性,由于其功能太强大,兼容性太差,我现在还没法驾驭它,所以没敢献丑,不过w3cplus有篇文章写的很好,感兴趣可以读一下http://www.w3cplus.com/css3/using-flexbox-today.html。

    弹性布局因为其兼容性所以还没有得到广泛的认可,不过我觉得以后它肯定会独占鳌头,就跟我看好html的视频播放器一样,早晚都会干败flash,只是时间问题!!!

    第六种:transform:translate

      CSS3中用于动画的一个样式,但是他可是让两个元素横向排列,这里不多说直接上代码,请用谷歌浏览器运行一下:

    <style>        div{            width:200px;    height:200px;        }        .box1{            background:green;        }        .box2{            transform: translateX(200px) translateY(-200px);            background:red;        }    </style><br />

    <div>    <div class = "box1">左边</div>    <div class = "box2">右边</div></div>

    效果和前几种方式一样。

    以上就是我说分享实现横向布局的六种方式,其实每种方式都有很多大学问,我解释描述了冰山一角,并且没有过多的考虑浏览器的兼容性,不过还是希望对你有所帮助。

     

    如有错误,请指正,

    如果你有其它方式,请留言补充

    感谢

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

    The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

    Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

    HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

    What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

    The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

    HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

    The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

    How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

    Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

    What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

    HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

    How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

    TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

    HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

    HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Article

    Hot Tools

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor