Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make button's width autofit the text of a button?

Tags:

.net

styles

wpf

I am currently doing this, but I am doing something wrong :):

   <Style TargetType="{x:Type Button}">
      <Setter Property="MinWidth" Value="90" />
      <Setter Property="Width" Value="Auto" />
   </Style>

I want the buttons to have some minimum width but also to have their width expand to fit the text of the button.

like image 934
Alex Baranosky Avatar asked Sep 11 '09 07:09

Alex Baranosky


People also ask

How do I make text fit a button in CSS?

Remove the width and display: block and then add display: inline-block to the button. To have it remain centered you can either add text-align: center; on the body or do the same on a newly created container.

How do you make a button occupy full width?

display: block and width: 100% is the correct way to go full width but you need to remove the left/right margin on the button as it pushes it outside the containing element. for more information on the box-sizing property, read the MDN docs.

How do I increase the size of the button text?

To change the font size of a button, use the font-size property.


2 Answers

What you have to do is set the HorizontalAlignment property to Center (or Right or Left). The buttons must be getting stretched by the containing Panel.

   <Style TargetType="{x:Type Button}">
      <Setter Property="MinWidth" Value="90" />
      <Setter Property="HorizontalAlignment" Value="Center" />
   </Style>
like image 132
Alex Baranosky Avatar answered Oct 06 '22 01:10

Alex Baranosky


If setting HorizontalAlignment isn't working, check to see that you have not set a Width - that will prevent the button from resizing. A handy trick is setting the Width property to NaN or ..NaN depending upon your application's configuration (which ever doesn't throw a compilation error).

like image 35
Thomas Avatar answered Oct 06 '22 00:10

Thomas