字体少的时候居中显示,多的时候居左显示,在实际应用中还是比较常用的,那么该怎么实现呢,
(1)如果不使用弹性布局的情况下,父元素设置text-align:center,子元素设置display: inline-block(或者inline-flex),text-align:left;实现
.ceshi{ width: 100px; padding: 10px 20px; border-radius: 4px; color: #fff; background: red; text-align: center; } .ceshi span{ display: inline-block; text-align: left; } </style> <body> <div class="ceshi"><span>哈哈</span></div> </body>
(2)使用弹性布局,只要父元素设置display: flex; justify-content: center;子元素无需设置
.ceshi{ width: 200px; padding: 10px 20px; border-radius: 4px; color: #fff; background: red; display: flex; justify-content: center; } </style> <body> <div class="ceshi"><span>哈哈</span></div> </body>